Cors Nginx和Node.js

时间:2018-06-24 10:49:01

标签: node.js reactjs nginx cors

我在客户端使用ReactJS,在后端使用NODEJS,将nginx用作反向代理。 我的nginx文件看起来像这样。

============================= test session starts =============================
platform win32 -- Python 2.7.14, pytest-3.6.1, py-1.5.3, pluggy-0.6.0
rootdir: C:\PycharmProjects\TestingFramework, inifile:
plugins: tap-2.2, report-0.2.1
collected 0 items

======================== no tests ran in 0.01 seconds =========================

即使以为在Nginx上启用了CORS,我在进行REST调用时在ReactJS端也会出错。

server{
            listen 80;
            server_name www.trusting.com;
            location / {

                    proxy_set_header 'Access-Control-Allow-Origin' 'http://localhost:3000';
                    proxy_set_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
                    proxy_set_header 'Access-Control-Allow-Headers' 'X-Requested-With,Accept,Content-Type, Origin';

                    proxy_pass http://localhost:8080;
                    proxy_http_version 1.1;
                    proxy_set_header Upgrade $http_upgrade;
                    proxy_set_header Connection 'upgrade';
                    proxy_set_header Host $host;
                    proxy_cache_bypass $http_upgrade;





        }


    }

1 个答案:

答案 0 :(得分:1)

根据to the documentationproxy_set_header将标头附加到请求。这样做时,请求尚未进入您的nodeJS应用程序。

您需要做的是attach a header to the response。为此,您需要使用add_header指令:

server {
        listen 80;
        server_name www.trusting.com;
        location / {

            add_header 'Access-Control-Allow-Origin' 'http://localhost:3000' always;
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
            add_header 'Access-Control-Allow-Headers' 'X-Requested-With,Accept,Content-Type, Origin' always;

            proxy_pass http://localhost:8080;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
    }
}