To set a base URL for NodeJS app, we create a router object.
For instance, we write
const express = require("express");
const app = express();
const router = express.Router();
router.use((req, res, next) => {
console.log("%s %s %s", req.method, req.url, req.path);
next();
});
router.use("/bar", (req, res, next) => {
next();
});
router.use((req, res, next) => {
res.send("Hello World");
});
app.use("/foo", router);
app.listen(3000);
to create a router
with express.Router
.
Then we call use
to add the route middlewares.
Next, we call app.use
with the base URL and the router
to add the routes for the base path.