I have a React frontend served by Nginx, requesting a Flask API that is served by Gunicorn combined with Nginx (acting as a reverse proxy). Both frontend and backend run on the same machine, on ports 3000 and 8000 respectively. That means that the frontend requests the backend on 127.0.0.1:8000
.
While testing in my local dev environment, all works as expected. On the other hand, the app deployed on a VPS doesn’t: requesting http://public-ip-address:3000/
will return:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource
at http://127.0.0.1:8000/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Status code: 200.
I am aware of the Same Origin Policy which requires to manage CORS. I do this in the Flask API as follows:
CORS(
app,
resources={
r"/*": {
"origins": [
"http://localhost:3000/",
"http://127.0.0.1:3000/",
"http://public-ip-address:3000/"
]}},
supports_credentials=True
)
So my guess would be that I messed up the reverse proxy block file configuration:
server {
listen 8000;
server_name _;
# Custom headers for reverse proxy
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
location / {
include /etc/nginx/proxy_params;
proxy_pass http://unix:/path/to/unix/socket/file.sock;
# CORS headers for allowing cross-origin requests
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
}
for context and clarity, let me provide the frontend block file as well:
server {
listen 3000;
server_name _;
root /path/to/react/app/build;
index index.html;
location / {
try_files $uri $uri/ =404;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
I do realize that the question is quite basic, so let me apologize in advance for that, but I am really new to devops and deploying stuff. Thanks in advance to whoever will kindly take the time.