情况2:
Access to XMLHttpRequest at 'http://localhost:22222/api/Login/TestGet' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
通过报错信息提示可以得知,是跨域浏览器默认行为的预请求(option请求)没有收到ok状态码,此时再修改配置文件,当请求为option请求时候,给浏览器返回一个状态码(一般是204)
server { listen 22222; server_name localhost; location / { add_header Access-Control-Allow-Origin 'http://localhost:8080' always; if ($request_method = 'OPTIONS') { return 204; } proxy_pass http://localhost:59200; } }
当配置完后,发现报错信息变了
情况3:
Access to XMLHttpRequest at 'http://localhost:22222/api/Login/TestGet' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
意思就是预请求响应头Access-Control-Allow-Headers中缺少头信息authorization(各种情况会不一样,在发生跨域后,在自定义添加的头信息是不允许的,需要添加到请求响应头Access-Control-Allow-Headers中,以便浏览器知道此头信息的携带是服务器承认合法的,我这里携带的是authorization,其他的可能是token之类的,缺什么加什么),知道了问题所在,然后修改配置文件,添加对应缺少的部分,再试试
server { listen 22222; server_name localhost; location / { add_header Access-Control-Allow-Origin 'http://localhost:8080' always; if ($request_method = 'OPTIONS') { add_header Access-Control-Allow-Headers 'authorization'; #为什么写在if里面而不是接着Access-Control-Allow-Origin往下写?因为这里只有预检请求才会检查 return 204; } proxy_pass http://localhost:59200; } }
此时发现报错问题又回到了情况1
'
经测试验证,只要if ($request_method = 'OPTIONS') 里面写了 add_header ,当为预检请求时外部配置的都会失效,为什么?↓↓。
官方文档是这样说的:
There could be several add_header directives. These directives are inherited from the previous level if and only if there are no add_header directives defined on the current level.
意思就是当前层级无 add_header 指令时,则继承上一层级的add_header。相反的若当前层级有了add_header,就应该无法继承上一层的add_header。
配置修改如下:
server { listen 22222; server_name localhost; location / { add_header Access-Control-Allow-Origin 'http://localhost:8080' always; if ($request_method = 'OPTIONS') { add_header Access-Control-Allow-Origin 'http://localhost:8080'; add_header Access-Control-Allow-Headers 'authorization'; return 204; } proxy_pass http://localhost:59200; } }
此时改完发现跨域问题已经解决了,
不过以上虽然解决了跨域问题,但是考虑后期可能Nginx版本更新,不知道这个规则会不会被修改,考虑到这样的写法可能会携带上两个 Access-Control-Allow-Origin ,这种情况也是不允许的,下面会说到。所以配置适当修改如下:
server { listen 22222; server_name localhost; location / { if ($request_method = 'OPTIONS') { add_header Access-Control-Allow-Origin 'http://localhost:8080'; add_header Access-Control-Allow-Headers 'authorization'; return 204; } if ($request_method != 'OPTIONS') { add_header Access-Control-Allow-Origin 'http://localhost:8080' always; } proxy_pass http://localhost:59200; } }




