gpt4 book ai didi

node.js - Cors nginx 和 nodejs

转载 作者:太空宇宙 更新时间:2023-11-04 03:02:37 26 4
gpt4 key购买 nike

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

最佳答案

根据to the documentation , proxy_set_header 将 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;
}
}

关于node.js - Cors nginx 和 nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51009175/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com