nginx,上游,cors失败

时间:2014-05-05 17:43:10

标签: node.js nginx cors

无法理解我的上游/ CORS配置失败的原因。这阻止了一些本地开发和测试。

我获得了 No' Access-Control-Allow-Origin'在从 local.mysite.com:8081 events.mysite.com 发出API请求时,请求资源上存在标题

这是来自/ etc / nginx / sites-available / mysite

的服务器配置
# the IP(s) on which your node server is running. I chose port 3000.
upstream mysite {
    server 127.0.0.1:3000;
}

# the nginx server instance
server {
    listen 0.0.0.0:80;
    server_name mysite events.mysite.com;
    access_log /var/log/nginx/mysite.log;

    # pass the request to the node.js server with the correct headers and much more can be added, see nginx config options
    location / {
      proxy_set_header Access-Control-Allow-Origin *;
      # proxy_set_header 'Access-Control-Allow-Credentials' 'true';   # i've tried with and without this setting
      proxy_set_header 'Access-Control-Allow-Headers' 'X-Requested-With,Accept,Content-Type, Origin';
      proxy_set_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';

      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;

      proxy_pass http://app_mysite/;
      proxy_redirect off;
    }
 }

,我尝试在Access-Control- *选项中使用 add_header 而不是proxy_set_header,但也没有骰子。

我正在运行Node.js应用。我没有修改节点代码来处理CORS ...是我的nginx配置错误,还是没问题但是我需要在Node中做其他事情?

1 个答案:

答案 0 :(得分:1)

必须将CORS标头提供给浏览器,而不是节点应用程序。因此,您应该使用add_header指令,或者更好地在应用程序中设置这些标头。这应该足够了。如果您确实使用withCredentials取消注释相应的行。如果您使用的东西使浏览器发送预检请求,您应该正确处理' OPTIONS'请求。

location / {
  add_header Access-Control-Allow-Origin *;
  # add_header Access-Control-Allow-Credentials true;

  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header Host $http_host;
  proxy_set_header X-NginX-Proxy true;

  proxy_pass http://app_mysite/;
  proxy_redirect off;
}