服务端解决跨域
1. 使用 addCorsMappings方式
- sping中可以配置
addCorsMappings
, 如下@Configuration @EnableWebMvc public class ConfigurerAdapter implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowCredentials(true) .allowedHeaders("*") .allowedOrigins("*") .allowedMethods("GET","POST","PUT","DELETE"); } }
- 此种配置 , 生效在拦截器后 , 若我们设置了拦截器 , 则此种方式会失效
2. 使用 corsFilter方式
- 可以使用设置
corsFilter
的方式解决跨域问题 , 因为Filter
在Interceptor
执行 , 所以不会有上述的失效问题 - 代码设置如下
@Configuration @EnableWebMvc public class ConfigurerAdapter implements WebMvcConfigurer { @Bean public 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); } }