解决跨域Access-Control-Allow-Origin 设置无效问题

1,159次阅读
没有评论

在开发或使用别人项目的过程中,经常会遇到跨域访问失败的问题,解决这种问题的方法也很简单,就是在 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 设置无效问题

上图中可以看到返回了多个 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’; 即可

正文完
 
ddn
版权声明:本站原创文章,由 ddn 2021-05-26发表,共计1099字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。