Sometimes, we want to add a single routing handler for multiple routes in a single line with JavaScript Express.
In this article, we’ll look at how to add a single routing handler for multiple routes in a single line with JavaScript Express.
Add a Single Routing Handler for Multiple Routes in a Single Line with JavaScript Express
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.
Conclusion
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.