平时后端只需要写一个配置类就可以解决跨域但是最近的新项目死活不行
先说结论
项目中的权限校验(也可以是其他的)拦截器优先级高于跨域拦截器导致跨域处理失效
解决办法
1.在addCorsMappings上增加 @Order(value = -100)// 跨域优先级最高
2.nginx放行OPTIONS请求
SpringBoot3后端配置
跨域配置类如下
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {/*** 解决跨域** @param registry*/@Override@Order(value = -100)// 跨域优先级最高public void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOriginPatterns("*").allowedMethods("*").allowedHeaders("*").exposedHeaders("*").allowCredentials(true).maxAge(3600);}
}
权限校验配置类(和跨域拦截器优先级冲突)
@Configuration
public class SecurityWebMvcConfig implements WebMvcConfigurer {// 忽略的路由ArrayListprivate static final List<String> IGNORE_URI =Arrays.asList("/user/login","/user/register","/user/validateKey");/*** 查询用户信息注入拦截器** @return*/@Bean@Order(value = 2147483600)public LoginUserInterceptor loginUserInterceptor() {return new LoginUserInterceptor();}@Bean@Order(value = 2147483601)public LoginInterceptor pigLoginInterceptor() {return new LoginInterceptor();}// 注意这里添加的拦截器也是拦击全部路径的,@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(loginUserInterceptor()).excludePathPatterns(IGNORE_URI).addPathPatterns("/**");registry.addInterceptor(pigLoginInterceptor()).excludePathPatterns(IGNORE_URI).addPathPatterns("/**");}}
以下方法无用,不是根本原因可以忽略,只需要配置好后端即可
解决未遂
但是目前还是没有根本上解决问题现在依然会报错,大致意思就是预校验OPTIONS请求没有被放行,包含不被允许的header,没通过,我不理解为啥没通过
Access to XMLHttpRequest at '后端域名' from origin '前端域名' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
OpenResty配置
所以又在OpenResty/nginx上配置了放行OPTIONS请求的配置
location / {if ($request_method = 'OPTIONS') {add_header 'Access-Control-Allow-Origin' '*';add_header 'Access-Control-Allow-Methods' '*';add_header 'Access-Control-Allow-Headers' '*';add_header 'Access-Control-Max-Age' 1728000;add_header 'Content-Type' 'text/plain; charset=utf-8';add_header 'Content-Length' 0;return 200;}proxy_pass http://127.0.0.1:11111;}
注意OpenResty/nginx不可以重复放行其他请求,重复放行会报错
Access to XMLHttpRequest at '后端域名' from origin '前端域名' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '前端域名, *', but only one is allowed.
具体问题就处在header contains multiple values '前端域名, *',
意思就是包含多个允许的请求源,一般返回一个就行了