文章

浏览器出现的一些跨域的问题,如何正确设置cors

浏览器出现的一些跨域的问题

1.预检请求问题,就是会以options的方法发送请求

比如你有如下nginx配置

location / {  
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

    if ($request_method = 'OPTIONS') {
        return 204;
    }
} 

浏览器会报如下错误:

Access to fetch at 'https://example.com/api/send' from origin 'https://example2.com' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

这时候变更nginx的配置如下就好了:

location / {  
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
   # 去掉以下配置就可以了 
   # if ($request_method = 'OPTIONS') {
   #     return 204;
   # }
} 

2.返回了多个Access-Control-Allow-Origin响应头问题

比如你有如下nginx配置

location / {  
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
} 

浏览器会报如下错误:

Access to fetch at 'https://example.com/api/send' from origin 'https://example2.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

这时候变更nginx的配置如下就好了,就去掉允许所有源,因为服务器可能已经设置过了,nginx不用再设置了

location / {  
  # 去掉以下这行就可以了
  # add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
} 

许可协议:  CC BY 4.0