原文:
SpringBoot中addCorsMappings配置跨域与拦截器互斥问题的原因研究_黄亚的博客-CSDN博客
springboot后端跨域addCorsMappings与拦截器冲突导致跨域失效_小咸白鱼的博客-CSDN博客_springboot拦截器导致跨域失效
大佬在上:(手动加粗,加粗,加粗...)
前言:
前端使用Angular,在token过期后,前端在响应体中拿取不到过期的响应信息(准确来说,是这次请求挂掉了,请求飘红,根本就没有响应信息),在查看浏览器控制台和网络,报跨域。重浏览器错误信息中看是跨域问题,但是其它请求都是能正常请求和响应,感觉跨域说不通,最后在网上查找资料,说的是在拦截器中的一个先后执行过程,类似于请求在拦截器中时,是不会执行WebMvcConfigurer中的跨域配置:
原拦截器及跨域配置:
@Configuration
public class WebInterceptorConfig implements WebMvcConfigurer {
/**
* 拦截路径
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new WebInterceptor())
.addPathPatterns("/**") // 拦截所有请求
.excludePathPatterns("/admin/login") // 放行登录请求
.excludePathPatterns("/admin/logout") // 放行登出
.excludePathPatterns("/cas/**"); // 放行CAS
}
/**
* 开启跨域
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
// 设置允许跨域的路由
registry.addMapping("/**")
// 设置允许跨域请求的域名
.allowedOriginPatterns("*")
// 是否允许证书(cookies)
.allowCredentials(true)
// 设置允许的方法
.allowedMethods("*")
// 允许的请求头
.allowedHeaders("*")
// 跨域允许时间
.maxAge(3600);
}
}
解决方式:
逻辑:让请求到拦截器前先完成跨域问题的解决,Filter过滤器是先于Interceptor拦截器执行的,所以取消上代码在拦截器中的“开启跨域配置”。
新建Filter,用于跨域问题解决:
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 MyCorsFilter{
private CorsConfiguration corsConfig(){
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedHeader("*"); //允许所有域名访问
corsConfiguration.addAllowedMethod("*"); //允许所有请求头
corsConfiguration.addAllowedOrigin("*"); //允许所有的请求类型
corsConfiguration.setMaxAge(3600L);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter(){
//存储request与跨域配置信息的容器,基于url的映射
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**",corsConfig());
return new CorsFilter(source);
}
}
总有人间一两风,填我十万八千梦。