【问题标题】:Handling CORs inside of node behind nginx在 nginx 后面的节点内部处理 COR
【发布时间】:2014-04-14 07:34:31
【问题描述】:

目前我正在处理 node.js 中的 COR,这似乎工作得很好;我可以设置多个域并点击我的 node.js 代码就好了。

问题是,一旦我将 node.js 放入永远,并从 nginx 到我的应用程序运行代理,它就不再处理任何 CORs 请求。事实上,他们甚至从来没有进入服务器,我很难弄清楚为什么。下面是我的 nginx 配置;有什么建议?如果不是很明显,我会尝试从 webapp.org 访问 services.org。在这个环境中,它们在同一个盒子上,但在其他环境中,当被第三方使用时,我们需要 COR 工作。

   server {
    listen       80;
    server_name  webapp.org;

    location / {
        proxy_pass http://localhost:3000/Site/;
        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;
    }
}

server {
    listen       80;
    server_name  services.org;

    location / {
        proxy_pass http://localhost:3000;
        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;
    }
}

【问题讨论】:

    标签: node.js nginx cors


    【解决方案1】:

    在 nginx.conf 中尝试使用 127.0.0.1 而不是 localhost

    【讨论】:

    • 我在 Ryan 的回答下试过这个,但似乎没有什么不同。
    【解决方案2】:

    尝试像这样添加上游服务器:

    upstream my_app {
        server 127.0.0.1:3000;
    }
    
    server {
        listen 0.0.0.0:80;
        server_name webapp.org;
        access_log /var/log/nginx/my_app.log;
    
        # pass the request to the node.js server with the correct headers and much more can be added, see nginx config options
        location / {
          root /var/www/my_app/public;
          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_redirect off;
          if (!-f $request_filename) {
            proxy_pass http://my_app;
            break;
          }
        }
     }
    

    【讨论】:

    • 我更新了我的配置以使用上游和 127.0.0.1 而不是 localhost 但没有好处。实际上,我完全复制并粘贴了您的整个配置,调整了 server_name 之类的明显内容,但仍然没有运气。
    • 很奇怪...我在我的设置中使用了这个配置并且对 CORS 没有任何问题。当你用永远启动节点时,你还能在 3000 端口点击节点吗?
    【解决方案3】:

    您可能需要通过以下方式为服务启用 CORS:

    app.enableCors() 在 main.ts 中的 bootstrap() 函数中

    【讨论】:

      猜你喜欢
      • 2021-10-10
      • 2017-10-04
      • 1970-01-01
      • 2021-08-08
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 2015-08-26
      • 1970-01-01
      相关资源
      最近更新 更多