In this article, we’ll look at how to get the multiple URL parameters in JavaScript Express routes.
To accept multiple URL parameters in JavaScript Express routes, we can put them as the placeholders for each URL parameter in the route path string.
For instance, we can write:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('hello world')
});
app.get('/fruit/:fruitName/:fruitColor', (req, res) => {
const { fruitName, fruitColor } = req.params;
res.json({ fruitName, fruitColor });
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
We add the ‘/fruit/:fruitName/:fruitColor’
route, where :fruitName
and :fruitColor
are the URL params placeholders.
We can get the values of them from the req.params
object.
Then, we return the extracted parameter values in the response object with res.json
.
So if we make a GET request to /fruit/apple/green
, we see:
{ "fruitName": "apple", "fruitColor": "green" }
returned as the response.
Total Views: 2,407