![Alt](https://img-home.csdnimg.cn/images/20220524100510.png =60x60
1、首先排查请求的项目中是否配置跨域代码(新人容易犯的错误),如果有去掉。
2、其次排查自己项目中是否有网关,网关服务有配置跨域,如果有去掉。
3、最后在NGINX中配置跨域统一在location中配置。
2-1、如果只有网关,网关自身是有去重响应头的过滤器,配置在路由中将重复的响应头过滤掉即可。
3-1、如果也是在NGINX中配置跨域:
3-1.1、 在上文所说 在location中配置:
location /cc{
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, DELETE, PUT, OPTIONS';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Access-Control-Allow-Headers' ',Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 200;
}
proxy_pass “你的后端服务访问URL”;
}
3-1.2、 在NGINX全局中配置:
http {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods HEAD,OPTIONS,GET,POST,PUT,DELETE;
}
如果在集成第三方API的需求时,第三方提供的接口也处理了跨域的配置,此时自己项目系统的NGINX中全局中都配置了跨域处理,就会出现响应头重复的问题,对于新接手这些项目系统的开发人员是个头疼的问题。
在3-1.1处理方式中增加以下配置:
location /jintaike {
add_header Access-Control-Allow-Origin "";
add_header Access-Control-Allow-Methods "";
add_header Access-Control-Allow-Headers "";
}
location /cps/api/gs-guide-websocket {
if ( $http_origin ~ http://(.*).xxx.xxxx.com){
set $allow_url $http_origin;
}
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Origin' '$allow_url';
add_header 'Access-Control-Allow-Methods' 'GET, POST, DELETE, PUT, OPTIONS';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Access-Control-Allow-Headers' ',Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 200;
}
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Origin' '$allow_url';
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $Http_host;
proxy_set_header Origin ""; #"http://api.xxx.xxx.com";
proxy_set_header X-Requested-For $remote_addr;
proxy_pass http://xxx;
}