Access to XMLHttpRequest at 'https://xxxxx' from origin 'https://aaaa' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
在使用Nginx 进行反向代理 后,并设置了 'Access-Control-Allow-Origin' 为 * ,这个时候出现了上述错误。这个时候 只能去指定 特定的域名 才能去访问,但是我又想允许其它域名访问,允许跨域,这个时候可以如下设置:
首先如果我们的程序后端有设置"Access-Control-Allow-Origin",在进行方向代理时,为了不受后端 Access-Control-Allow-Origin 的影响,我们应该先进行屏蔽,
proxy_hide_header Access-Control-Allow-Origin;
之后我们在代理文件的末尾增加如下判断:(当请求时,会默认将其设置为允许跨域的域名)
# 设置 CORS 相关响应头
if ($http_origin = "") {
add_header Access-Control-Allow-Origin *;
}
if ($http_origin != "") {
add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Credentials 'true';
}
下面是一个完整的反响代理配置
#PROXY-START/
location ^~ /
{
proxy_pass http://127.0.0.1:5566;
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 REMOTE-HOST $remote_addr;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_http_version 1.1;
proxy_hide_header Access-Control-Allow-Origin;
# proxy_hide_header Upgrade;
add_header X-Cache $upstream_cache_status;
#Set Nginx Cache
set $static_filePsaFwnAU 0;
if ( $uri ~* "\.(gif|png|jpg|css|js|woff|woff2)$" )
{
set $static_filePsaFwnAU 1;
expires 1m;
}
if ( $static_filePsaFwnAU = 0 )
{
add_header Cache-Control no-cache;
}
# 设置 CORS 相关响应头
if ($http_origin = "") {
add_header Access-Control-Allow-Origin *;
}
if ($http_origin != "") {
add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Credentials 'true';
}
}
#PROXY-END/