I am getting cors issue in one of the Poc I am working on.Backend Apis are behind the Nginx proxy server and if any try to hit proxy, Browser is complaining Cors issue.
If I try with the actual endpoint of API services,I don’t see any errors.I am assuming, I have to fix this at the Nginx level rather than adding proxy config in react app level.
I have tried most of the solutions available in online forum. Could anyone please help me if I have missed anything to rectify error .
React app is running on port 3000 and Nginx is running on port 80.
Proxy settings in 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;
}
}
Error:
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
I am attaching docker-compose file and nginx.conf and default.conf here
2
Answers
Final Solution on above issue:
Based on the error message, it looks like your request is sending a header called
authorization
, but that is not included in the config you’ve provided.YOu might need to change this line:
to this:
If that doesn’t work, I’d recommend looking more closely at the network info in the network tab of your browser, and looking at the
OPTIONS
preflight request that the browser is sending.