Categories
Express JavaScript Answers

How to Accept Multiple URL Parameters in Express Routes?

Spread the love

To accept multiple URL parameters in 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.

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 *