跨域场景:
场景:springboot + vue2 前后端分离;前端接口为localhost:8080 后端要请求的接口为localhost:9000/login/query(post方式)
前端跨域
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave: false, //关闭eslint检查
devServer: {
host: 'localhost',
port: process.env.PORT || 8081 || 8082,
open: true,
proxy: {
[process.env.VUE_APP_BASE_API]: {
target: 'http://localhost:9000',//要跨域的域名
secure: false, //如果是https接口,如要配置此参数
changeOrigin: true,//允许跨域
pathRewrite: {
["^" + process.env.VUE_APP_BASE_API]: "",
},
}
},
historyApiFallback: true, // 在 webpack5的特性,代替之前的 disableHostCheck
allowedHosts: "all",
},
})
后端跨域:
@Configuration
public class CorsConfig {
@Bean
public FilterRegistrationBean corsFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
//是否允许请求带验证信息
config.setAllowCredentials(true);
//前端对应的域名
config.addAllowedOrigin("http://localhost:8080");
//允许访问客户端请求头
config.addAllowedHeader("*");
//允许访问的方法名
config.addAllowedMethod("*");
// CORS 配置对所有接口都有效
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}
踩坑:
如果跨域没配置好,就可能访问不了。有时候前端会出现请求两次的情况,一次是options预检查,另一次是成功的情况,这种是跨域没配置完整,需检查好配置项。