skip to Main Content

I have prepared a front-end, and the file is placed in
/usr/local/var/www/front-end

Then there is an express backend, a simple get example that returns a "yes" string, already started by express, with port 3000

——– express ——–

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('yes')
});

app.listen(port, () => {
  console.log('The : ' + port + 'are listen');
});

Now I want nginx to listen to the front-end, port 1155, and then set up a route, like an api, which will be proxied by nginx to port 3000

I did this test.

——– nginx ——–

server {
        listen 1155;
        server_name demo.com;
        location / {
            root /usr/local/var/www/front-end;
            index index.html;
        }
        location /api/ {
            proxy_pass http://127.0.0.1:3000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
        }
    }

However, when I test http://127.0.0.1:1155/api/ in postman, nginx only returns Cannot GET /api/

What am I doing wrong? I keep trying various combinations, but always fail, I can barely figure out the relationship between location and root, I hope this simple test will help me understand, thanks.

2

Answers


  1. Alternative 1:
    Remove the /api prefix from the url when forwarding it to the backend.

    location /api/ {
      rewrite ^/api(.*) /$1 break;
      proxy_pass http://127.0.0.1:3000;
      …
    }
    

    Alternative 2:
    Mount the backend server on /api

    app.get('/api/', (req, res) => {
      res.send('yes')
    })
    
    Login or Signup to reply.
  2. An even cleaner way would be adding trailing / for the proxy_pass’s value. NGINX will replace matched part (/api/) with provided URI /:

    location /api/ {
      proxy_pass http://127.0.0.1:3000/;
      …
    }
    

    Thanks to that, GET http://nginx/api will be proxied to the GET http://127.0.0.1:3000/.

    You can read more about this in the nginx documentation.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search