nginx, upstream, cors fail

2019-07-20 01:42发布

问题:

Can't grasp why my upstream / CORS config is failing. This is preventing some local dev and testing.

I'm getting a No 'Access-Control-Allow-Origin' header is present on the requested resource when making an API request from local.mysite.com:8081 to events.mysite.com.

Here is my server config from /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;
    }
 }

also, I tried using add_header and not proxy_set_header on the Access-Control-* options, but no dice there either.

I'm running a Node.js app. I have not modified the Node code to handle CORS... is my nginx config wrong, or is it fine but I need to do something else in Node?

回答1:

CORS headers have to be served to browser, not your node application. So you should use add_header directive or, better, set these headers in your application. This should be enough. If you do use withCredentials uncomment appropriate line. If you use something that makes browser to send preflight request, you should properly handle 'OPTIONS' request.

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;
}