Nginx CORS' Access-Control-Allow-Origin'头

时间:2018-04-10 07:06:36

标签: reactjs nginx cors

我已使用以下配置配置Nginx反向代理:

location ^~ /api/my-service/ {
    if ($request_method = 'OPTIONS') {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, HEAD';
    add_header 'Access-Control-Allow-Headers' 'Authorization,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    add_header 'Access-Control-Max-Age' 1728000;
    add_header 'Content-Type' 'text/plain; charset=utf-8';
    add_header 'Content-Length' 0;
    return 200;
 }
 if ($request_method = 'GET') {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'Authorization, DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
 }
}

当从不同的来源调用此服务时,在网络选项卡中,我会看到服务的响应,例如: http://nginx-host/api/my-service/users/user 响应头是:

Cache-Control   no-cache, no-store, max-age=0, must-revalidate
Connection  keep-alive
Content-Type application/json;charset=UTF-8
Date    Tue, 10 Apr 2018 07:54:40 GMT
Expires 0
Pragma  no-cache
Server  nginx/1.10.3 (Ubuntu)
Transfer-Encoding chunked
X-Content-Type-Options nosniff
X-Frame-Options DENY
X-XSS-Protection 1; mode=block

在chrome / firefox的控制台中,我看到:

Failed to load http://nginx-host/api/my-service/users/user: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://10.11.13.202:2200' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

此调用是基于响应的应用程序进行的,我还应在请求标头中添加一些内容以便完成此操作。 OPTIONS响应已正确显示标题:

HTTP/1.1 204 No Content
Access-Control-Allow-Headers: Authorization,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range
Access-Control-Allow-Methods: GET, POST, OPTIONS, HEAD
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 1728000
Connection: keep-alive
Content-Length: 0
Content-Type: text/plain; charset=utf-8
Date: Tue, 10 Apr 2018 08:08:53 GMT
Server: nginx/1.10.3 (Ubuntu)

2 个答案:

答案 0 :(得分:0)

暴露的API是厚颜无耻的,对于GET请求,响应头被接受,理想情况下应该是200,NGINX在这种情况下不附加响应头并且混乱配置。杜!

答案 1 :(得分:0)

另一种方法是始终在*占位符旁边使用: add_header' Access-Control-Allow-Origin' ' *'总是; 作品!