最近在部署上线的过程中遇到了一个问题,项目在预发环境完美通过了测试,但是到线上环境就崩了。
浏览器报错:Access to fetch at http://24r03.com from origin htttp://www.baidu.com has been blocked CORS policy Access-Control-Allow-Origin header contains mutiple values 'http://www.baidu.com,* ' ,but only one is allowed ,Have the server send the header with a valid fetch the resource with CORS disable.
从报错来看,问题很明显,跨域处理中 ,allow-origin不可能指定多个域,更没有指定域和*共存的写法。
先排除代码侧问题 : 设置 allow-origin 时 只设置了一个域 ,并且使用的是 setHeader 并非addHeader ,
(setHeader 和 addHeader 的区别:是setHeader会覆盖之前设置的header 值 而 addHeader会直接添加)
代码不存在问题,那么根据预发没报错而线上出问题了,那就是可能跟环境有关 ,排查看浏览器返回的响应头里面的结果:
可以看到access-origin确实是多了 * ,而却 相应的server 指向的是nginx 。
响应头对应的意思:https://blog.csdn.net/Boboma_dut/article/details/79741162
那么就有可能是NGINX 处理了一次跨域。并且是在响应通过后端之后。
查看线上环境的nginx的配置,发现nginx配置确实处理了跨域。
nginx处理跨域:原文:https://blog.csdn.net/envon123/article/details/83270277
server {
listen 80;
server_name xxx.com;
location /xxx-web/papi {
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,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';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
root html;
index index.html index.htm;
proxy_pass http://127.0.0.1:7071;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 5;
}
location /xxx-web {
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,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';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
root html;
index index.html index.htm;
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 5;
}
location / {
root /var/www/xxx/wechat/webroot;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}