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

2fjabf4q  于 5个月前  发布在  Nginx
关注(0)|答案(2)|浏览(49)

我得到cors问题在我正在工作的一个Poc.后端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;
        }
}

字符串
错误:

Access to XMLHttpRequest at 'http://localhost/products' from origin 
'http://localhost:3000' has been blocked by CORS policy: **Request header field 
authorization is not allowed by Access-Control-Allow-Headers in preflight 
response**


我正在附加docker-compose文件和nginx.conf和default.conf here
x1c 0d1x的数据

nzkunb0c

nzkunb0c1#

根据错误消息,看起来你的请求正在发送一个名为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 preflight请求。

vwoqyblh

vwoqyblh2#

最终解决上述问题:
1.在NGINX代理default.conf中添加头文件
1.添加跨源标题并为 * 或相应的IP:Port赋值

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

add_header "Access-Control-Allow-Origin" "*";

add_header 'Access-Control-Allow-Credentials' 'true';

字符串
1.在反向代理或后端启用cors。如果我们在这两个地方都有cors,浏览器将报告错误

相关问题