Search code examples
reactjsnode.jsexpressnginxproxypass

Error 404 when accessing API via Nginx and Express


I have set up a server with Nginx to serve a React application and proxy_pass requests to an Express API. The Nginx configuration includes a location block to proxy requests prefixed with /api/ to my Express server running on port 3001. Here's a snippet of my Nginx configuration:

server {
    server_name example.com;

    root /var/www/example.com/html;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }

    location /api/ {
        proxy_pass http://localhost:3001/;
        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;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

When I attempt to access the API endpoint https://example.com/api/posts, I receive a 404 Not Found error. However, accessing http://localhost:3001/api/posts directly on the server returns the expected data.

Here is an excerpt from the Nginx access log showing the 404 error:

192.168.1.1 - - [27/Jun/2024:12:34:56 +0000] "GET /api/posts HTTP/1.1" 404 144 "https://example.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.0.0 Safari/537.36"

I have verified that:

My Express server is running and listening on port 3001. The /api/posts route is correctly defined in my Express application. I have restarted Nginx after making configuration changes. There are no apparent firewall issues blocking the connection. Despite these checks, Nginx continues to return a 404 error when attempting to proxy requests to /api/ endpoints. I'm seeking advice on what might be causing this issue and how to resolve it.


Solution

  • It was a CORS and NGINX conf problem (I had to remove some stuff in my nginx conf): Here was middleware.js before :

    app.use(cors({
      origin: 'http://localhost:3000',
      methods: ['GET', 'POST', 'PUT', 'DELETE'],
      credentials: true,
    }));
    

    and after

    app.use(cors({
      origin: process.env.NODE_ENV === 'production' ? ['https://example.com'] : 'http://localhost:3000',
      methods: ['GET', 'POST', 'PUT', 'DELETE'],
      credentials: true,
    }));