Categories
JavaScript Answers

How to make multiple route parameters optional in Node.js Express?

Spread the love

Sometimes, we want to make multiple route parameters optional in Node.js Express.

In this article, we’ll look at how to make multiple route parameters optional in Node.js Express.

How to make multiple route parameters optional in Node.js Express?

To make multiple route parameters optional in Node.js Express, we can put a question mark after each optional route parameter placeholder.

For instance, we write

app.get('/articles/:year?/:month?/:day?', (req, res) => {
  const {
    year,
    month,
    day
  } = req.params
  //...
})

to call .app.get with a route path that has the optional year, month, and day parameter as indicated by the ? after each parameter.

Then we get the year, month, and day parameter value from req.params.

Conclusion

To make multiple route parameters optional in Node.js Express, we can put a question mark after each optional route parameter placeholder.

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 *