浏览器状态码400并且OPTIONS请求跨域
1.SpringBoot项目跨域配置如下:
@Configuration
public class CorsConfiguration {
@Bean
public FilterRegistrationBean<CorsFilter> corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
org.springframework.web.cors.CorsConfiguration config = new org.springframework.web.cors.CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
final FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}
2.但是对于一些特殊情况,虽然配置了跨域,但依然不好使,例如下面这种情况:1
对于一个get请求 例如后台使用:@RequestParam(“pageNum”) String pageNum 接收一个字符串类型的数据。
而前端给了一个对象,请求例如:/sys/user/list?pageNum=${{pageNum}}
。 此处参数{pageNum}是一个结构表达式获取的对象。
那么前端依旧会报跨域异常:
Access to XMLHttpRequest at 'http://localhost:8080/sys/user/list?pageNum=[object%20Object]' from origin 'http://localhost:8001' has been blocked by
CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
对于第二种情况,暂时没有找到解决方法 ↩︎