CORS跨越的问题

总结一下迄今为止遇见的跨越问题。

前端报错:Access to XMLHttpRequest at 'http://localhost:8080/api/xxxx from origin 'http://localhost:8001' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:8001, *', but only one is allowed.

关键字:but only one is allowed.出现这个错误有几个情况,但原因都是重复设置了跨越,而请求只需要设置一次。

分为两种情况:

1.有Nginx作为分发:

  修改Nginx相关配置即可:

  add_header Access-Control-Allow-Origin *;

  add_header Access-Control-Allow-Methods GET,POST,OPTIONS;

  add_header Access-Control-Allow-Headers X-Requested-With;

 

2.没有设置nginx:

  1.网关配置了跨越设置:在nginx设置了跨域,又在网关zuul或者gateway里设置了跨域

  2.在网关设置了之后,又在业务代码里设置了跨越,比如在Controller里添加了@CrossOrigin注解

 

网关跨域配置:

@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

CorsConfiguration corsConfiguration = new CorsConfiguration();

//1、配置跨域
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);

source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}

  


 

上一篇:springboot 实现允许跨域请求


下一篇:报错:跨域问题解决 No ‘Access-Control-Allow-Origin‘ header is present on the requested resource.