Cors nginx 和 nodejs

Raj*_*rth 1 nginx node.js cors reactjs

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

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;





        }


    }
Run Code Online (Sandbox Code Playgroud)

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

Failed to load http://www.trusting.com/hey/signup: Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
Run Code Online (Sandbox Code Playgroud)

Ham*_*bot 8

根据文档proxy_set_header在请求中附加一个标头。当它这样做时,请求尚未进入您的 nodeJS 应用程序。

您需要做的是在响应中附加一个标头。为此,您需要使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)