服务器端添加了全局的跨域配置,但是却出现了跨域问题,分析了多次请求发现有一部分请求并没有出现跨域,没有出现跨域的请求刚好就是拦截器放行的地址,所以分析可能是权限拦截器处理在跨域处理之前进行导致跨域配置失效。
解决方法,改用过滤器CorsFilter 来配置跨域,由于Filter的位置是在Interceptor之前的(Filter之间通过order设置优先级),问题得到解决:
import com.gh.quanzi.interceptors.LoginInterceptor;
import com.gh.quanzi.utils.PrintUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/*** 是个配置,所以用 Configuration 注入到 ioc容器*/
@Configuration
public class WebConfig implements WebMvcConfigurer {/*** todo 跨域支持*/
// @Override
// public void addCorsMappings(CorsRegistry registry) {
// registry.addMapping("/**")
// .allowedOriginPatterns("*")
// .allowedHeaders("*")
// .allowCredentials(true)
// .allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS", "HEAD")
// .maxAge(3600 * 24);
// }@Autowiredprivate LoginInterceptor loginInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {// 添加loginInterceptor,由于loginInterceptor对全局接口进行了拦截// 所以需要excludePathPatterns针对某些接口放行PrintUtils.print("addInterceptors 请求");registry.addInterceptor(loginInterceptor).excludePathPatterns("/user/login","/user/register","/home/hello","/yml");}/*** 跨越配置*/@Beanpublic CorsFilter corsFilter() {CorsConfiguration config = new CorsConfiguration();// 设置允许跨域请求的域名config.addAllowedOrigin("*");// 是否允许证书 不再默认开启// config.setAllowCredentials(true);// 设置允许的方法config.addAllowedMethod("*");// 允许任何头config.addAllowedHeader("*");config.addExposedHeader("token");UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();configSource.registerCorsConfiguration("/**", config);return new CorsFilter(configSource);}}