其他分享
首页 > 其他分享> > CORS跨越的问题

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);
}

  


 

标签:Control,问题,设置,corsConfiguration,跨越,header,Access,CORS,跨域
来源: https://www.cnblogs.com/chihsien/p/14891812.html