Cors nginx 和 nodejs
Posted
技术标签:
【中文标题】Cors nginx 和 nodejs【英文标题】:Cors nginx and nodejs 【发布时间】:2018-12-03 04:26:40 【问题描述】:我在客户端使用 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;
即使在 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.
【问题讨论】:
我认为一个地方的 cors 就足够了。 添加这个proxy_set_header 'Access-Control-Allow-Origin' '*';另请参阅此链接“***.com/questions/47488382/…” 【参考方案1】:根据to the documentation,proxy_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;
【讨论】:
我还必须将“授权”附加到“访问控制允许标题”以上是关于Cors nginx 和 nodejs的主要内容,如果未能解决你的问题,请参考以下文章