React 应用程序被 Nginx 代理服务器的 CORS 策略阻止

问题描述 投票:0回答:1

我在我正在处理的 Poc 之一中遇到了 cors 问题。后端 API 位于 Nginx 代理服务器后面,如果有人尝试访问代理,浏览器会抱怨 Cors 问题。

如果我尝试使用 API 服务的实际端点,我不会看到任何错误。我假设,我必须在 Nginx 级别修复此问题,而不是在 React 应用程序级别添加代理配置。 我已经尝试了在线论坛中提供的大多数解决方案。如果我遗漏了任何内容来纠正错误,任何人都可以帮助我吗?

React 应用程序在端口 3000 上运行,Nginx 在端口 80 上运行。

Default.conf中的代理设置

server { listen 80; server_name localhost; resolver 127.0.0.11 valid=1s ipv6=off; location /products/ { add_header "Access-Control-Allow-Origin" "*"; add_header "Access-Control-Allow-Headers" "Origin, X-Requested-With, Content-Type, Accept"; add_header 'Access-Control-Allow-Credentials' 'true'; if ($request_method = 'OPTIONS') { return 204; } proxy_set_header Host $host; access_by_lua_file /usr/local/openresty/lualib/auth.lua; proxy_pass http://items-ms:9212/; proxy_http_version 1.1; proxy_set_header Connection ""; # proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Server $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } location / { add_header "Access-Control-Allow-Origin" "*"; add_header "Access-Control-Allow-Headers" "Origin, X-Requested-With, Content-Type, Accept"; add_header 'Access-Control-Allow-Credentials' 'true'; if ($request_method = 'OPTIONS') { return 204; } root /usr/share/nginx/html; try_files $uri /index.html; } }
错误:

从原点访问“http://localhost/products”处的 XMLHttpRequest “http://localhost:3000”已被 CORS 策略阻止:
请求标头字段
在预检中 Access-Control-Allow-Headers 不允许授权
回应

我正在附加 docker-compose 文件以及 nginx.conf 和 default.conf

here

reactjs nginx nginx-reverse-proxy
1个回答
0
投票
根据错误消息,您的请求似乎发送了一个名为

authorization

 的标头,但这未包含在您提供的配置中。

您可能需要更改此行:

add_header "Access-Control-Allow-Headers" "Origin, X-Requested-With, Content-Type, Accept";
对此:

add_header "Access-Control-Allow-Headers" "authorization, Origin, X-Requested-With, Content-Type, Accept";
如果这不起作用,我建议您仔细查看浏览器网络选项卡中的网络信息,并查看浏览器发送的 

OPTIONS

 预检请求。

© www.soinside.com 2019 - 2024. All rights reserved.