1. 程式人生 > 其它 >解決跨域Access-Control-Allow-Origin 設定無效問題

解決跨域Access-Control-Allow-Origin 設定無效問題

解決跨域Access-Control-Allow-Origin 設定無效問題

在開發或使用別人專案的過程中,經常會遇到跨域訪問失敗的問題,解決這種問題的方法也很簡單,就是在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