解决前后端不同端口号的跨域请求问题

解决前后端不同端口号的跨域请求问题

拟定前端端口号8000;后端端口号是8070

前端使用的Vue框架,默认数据信息存储在 .eve.development中,需要配置(修改)前端数据发送的路径
NODE_ENV=development
//设置VUE_APP_PREVIEW=false ,
VUE_APP_PREVIEW=false
//URL后接后端tomcat服务地址http://localhost:8070/
VUE_APP_API_BASE_URL=http://localhost:8070/

方式1,在后端启动文件同级目录,创建一个目录Corsconfig

package com.mashibing.config;
//当通过文件配置跨域请求时,则配置的是全局
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class Corsconfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 设置属性
// 允许跨域请求的地址,*表示所有
corsConfiguration.addAllowedOrigin("*");
// 跨域的请求头
corsConfiguration.addAllowedHeader("*");
// 跨域的请求方法
corsConfiguration.addAllowedMethod("*");
// 在跨域请求的时候使用同一个 Session
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//配置 可以访问的地址
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}

方式2,通过注解的方式,在需要和前端交互数据的页面配置注解@CrossOrigin

package com.mashibing.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin(origins = "*",methods = {},allowedHeaders = "*",allowCredentials = "true")
public class test {
@RequestMapping("/auth/login")
public String test1(){
System.out.println("Success");
return "";
}
}
posted @   爱豆技术部  阅读(1718)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
TOP
点击右上角即可分享
微信分享提示