问题是您的if条件不会在中发送父项中的标头
/。如果您检查飞行前响应标头,它将是
HTTP/1.1 204 No ContentServer: nginx/1.13.3Date: Fri, 01 Sep 2017 05:24:04 GMTConnection: keep-aliveAccess-Control-Max-Age: 1728000Content-Type: text/plain charset=UTF-8Content-Length: 0
那什么也没给。因此,有两种可能的解决方案。复制
add_header里面的if块也
server { listen 80; server_name api.localhost; location / { add_header 'Access-Control-Allow-Origin' 'http://api.localhost'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'; add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH'; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' 'http://api.localhost'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'; add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain charset=UTF-8'; add_header 'Content-Length' 0; return 204; } proxy_redirect off; proxy_set_header host $host; proxy_set_header X-real-ip $remote_addr; proxy_set_header X-forward-for $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:3000; }}或者您可以将其移动到位置块之外,以便每个请求都具有响应
server { listen 80; server_name api.localhost; add_header 'Access-Control-Allow-Origin' 'http://api.localhost'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'; add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH'; location / { 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; } proxy_redirect off; proxy_set_header host $host; proxy_set_header X-real-ip $remote_addr; proxy_set_header X-forward-for $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:3000; }}如果您只想在配置中允许CORS的某些位置。就像
/api这样,您应该使用标题创建模板conf
add_header 'Access-Control-Allow-Origin' 'http://api.localhost'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'; add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';
然后使用
include conf.d/corsheaders.conf;
在你的
OPTIONS块和
/api块。因此,仅允许将CORS用于
/api。如果您不在乎CORS的位置,则可以使用第二种方法将核心标头移动到服务器块



