How to define Node.js application context path? How to define Node.js application context path? nginx nginx

How to define Node.js application context path?


As you said it's better to do it in nginx config for the sake of context path independence from application code.

On the nginx side, you can set the context path with location directive and then you can remove the context path from path and send the request to the application. It can be done with a rewrite directive of nginx as follows:

    location /myapp/ {        rewrite ^/myapp/(.*)$ /$1 break;        ...    }

Thus, in nodejs (express) side You should suppose that the application is running under the root path (/) as you said.


You can use express router for this.

const express = require('express');const app = express();const http = require('http');const httpServer = http.createServer(app);const router = express.Router();const contextPath = '/api';router.get('/', function(req, res) {  res.send("you've reached the API endpoint");});app.use(contextPath, router);httpsServer.listen(9000));

A get request to host:9000/api/ will now return "you've reached the API endpoint".