控制台错误如下:
Access to XMLHttpRequest at 'https://xxx/xxx' from origin 'https://xxx' 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.
Access to XMLHttpRequest at 'https://xxx/xx' from origin 'https://xxx' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.
原因:项目中设置了双跨域配置导致的问题
解决方法:
删除或注解掉一处,只保留一个。
注释掉nginx上的相关配置
location / {
root /var/www/html/xxx/dist/;
index index.html;
# 配置响应请求
try_files $uri $uri/ /index.html$is_args$args;
}
location /api/ {
proxy_pass http://localhost:xx/;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
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;
}
后端代码不动
之后又出现 CORS 头缺少 'Access-Control-Allow-Origin' 跨域问题
已拦截跨源请求:同源策略禁止读取位于 https://xxx 的远程资源。(原因:CORS 头缺少 'Access-Control-Allow-Origin')。状态码:204。
已拦截跨源请求:同源策略禁止读取位于 https://xxx 的远程资源。(原因:CORS 请求未能成功)。状态码:(null)。
发现还是报错,对nginx配置文件进行如下修改:
location /api/ {
proxy_pass http://localhost:xx/;
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;
}
}
location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
root /var/www/html/xxx/dist/;
index index.html;
# 配置响应请求
try_files $uri $uri/ /index.html$is_args$args;
}