Categories
Express JavaScript Answers

How to Add a Single Routing Handler for Multiple Routes in a Single Line with Express?

Spread the love

To add a single routing handler for multiple routes in a single line with Express, we can pass in an array of route path patterns that will be handled by one route handler.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

const routes = ['/', '/foo', '/bar', '/baz/:id']
app.get(routes, (req, res) => {
  res.send('hello world')
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

We have the routes array that has strings with different route path patterns.

And we use it as the first argument of the app.get method.

Therefore, when we go to / , /foo , /bar or /baz with anything after it, we’ll see hello world displayed.

This also works with app.post , app.delete , app.put , and other route defining methods.

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 *