Categories
JavaScript Answers

How to add route with optional parameter after root in Node.js Express?

Spread the love

To add route with optional parameter after root in Node.js Express, we add a question mark after the route parameter placeholder.

For instance, we write

app.get("/api/v1/tours/:cId/:pId/:batchNo?", (req, res) => {
  console.log(req.params.cId);
  console.log(req.params.pId);
  console.log(req.params.batchNo);
});

to add the option batchNo route parameter.

We get its value from req.params.batchNo.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published. Required fields are marked *