在开发或使用别人项目的过程中,经常会遇到跨域访问失败的问题,解决这种问题的方法也很简单,就是在nginx或web框架中加入跨域配置。
以nginx为例,只需要在server{}中加入以下add_header参数即可
add_header 'Access-Control-Allow-Origin' * always; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'PUT,GET,POST,OPTIONS';
但是某些情况下即使加入了 Access-Control-Allow-Origin’ * 浏览器还是会报错
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.
has been blocked by CORS policy: The ‘Access-Control-Allow-Origin’ header contains multiple values ‘http://xxx.com, *’, but only one is allowed.
这种情况下,无论你把Access-Control-Allow-Origin里面的值改成*或是域名都不行,浏览器还是会报错的。
解决思路:
打开浏览器开发者工具,查看Response Headers中是否返回多个Access-Control-Allow-Origin
上图中可以看到返回了多个Access-Control-Allow-Origin,这是因为web框架中也设置了跨域返回导致的,你可以在web框架中设置关闭跨域header,也可以通过nginx删除返回的header
以php为例,nginx配置fastcgi_hide_header即可
location ~ \.php { root /data/web/; fastcgi_pass 127.0.0.1:9006; fastcgi_index index.php; fastcgi_hide_header Access-Control-Allow-Origin; include php_fcgi.conf; }
重启nginx,浏览器再次访问就不会报跨域错误了~
nginx -t && nginx -s reload
如果你是proxy代理,配置proxy_hide_header ‘Key’;即可