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.
CodePudding user response:
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')
})