Cors nginx and nodejs



我在客户端使用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;


}

}

即使认为 CORS 在 nginx 上已启用,我在进行 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.

根据文档,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;
}
}

最新更新