深圳幻海软件技术有限公司 欢迎您!

基于spring的微服务和vue的前后端分离的项目怎么配置跨域处理

2023-03-02

1.后端配置新建一个CrosConfig.java文件(配置类),允许任意请求发送importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;

1. 后端配置

新建一个CrosConfig.java文件(配置类),允许任意请求发送

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;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 跨域设置
* 2021/10/9 10:57
*/
@Configuration
public class CrosConfig implements WebMvcConfigurer {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.addAllowedMethod("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
return new CorsFilter(configSource);
}
}

2. 前端配置代理(前后端只要一个配置就行)

vue根目录下新建一个 vue.config.js 文件

// 方法一: 当前端只需要请求一个后端(服务)时,可以使用以下这种:
module.exports = {
devServer: {
proxy: 'http://localhost:5000' // 配置代理的服务器地址
}
}
  1. 优点:配置简单,请求资源时直接发给前端(8080)即可。
  2. 缺点:不能配置多个代理,不能灵活的控制请求是否走代理。
  3. 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源,即当前端存在请求的东西时,则直接返回前端的东西)
// 方法二:前端需要请求多个后端服务:用以下这种
module.exports = {
devServer: {
proxy: {
'/api': {// 匹配所有以 '/api1'开头的请求路径
target: 'http://localhost:5000',// 代理目标的基础路径
changeOrigin: true,
pathRewrite: {'^/api': ''} // 代理到服务器的时候,去除api路径
},
'/api2': {// 匹配所有以 '/api2'开头的请求路径
target: 'http://localhost:5001',// 代理目标的基础路径
changeOrigin: true,
pathRewrite: {'^/api2': ''}
}
}
}
}
/*
changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
changeOrigin默认值为true
*/
  1. 优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
  2. 缺点:配置略微繁琐,请求资源时必须加前缀