Categories
JavaScript Answers

How to set a base URL for NodeJS app?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.