ak85
ak85

Reputation: 4264

express handle multiple levels of req params

In my express app I want the below routes.

/regions

/regions/europe

/regions/europe/france

/regions/europe/france/paris

I currently have this working with the below setup but was wondering if there was a more concise approach? eg can you handle this all in one server.get?

At the moment if I just have the last part /regions/:region/:country/:city and go to /regions/europe/france I get a 404 page not found?

server.get('/regions/:region/', (req, res) => {
  const actualPage = '/regions'
  const queryParams = {
    region: req.params.region
  }
  app.render(req, res, actualPage, queryParams)
})

server.get('/regions/:region/:country', (req, res) => {
  const actualPage = '/regions'
  const queryParams = {
    region: req.params.region,
    country: req.params.country
  }
  app.render(req, res, actualPage, queryParams)
})

server.get('/regions/:region/:country/:city', (req, res) => {
  const actualPage = '/regions'
  const queryParams = {
    region: req.params.region,
    country: req.params.country,
    city: req.params.country
  }
  app.render(req, res, actualPage, queryParams)
})    

Upvotes: 0

Views: 114

Answers (2)

YouneL
YouneL

Reputation: 8369

You can pass an array of routes to the get method, here is an example:

server.get([
    '/regions/:region',
    '/regions/:region/:country',
    '/regions/:region/:country/:city'
], (req, res) => {

    const actualPage = '/regions'

    const queryParams = req.params

    res.render(req, res, actualPage, queryParams)
})

Upvotes: 1

user5734311
user5734311

Reputation:

This should be pretty much equivalent:

const handleRegion = (req, res) => {
  app.render(req, res, '/regions', req.params)
}

server.get('/regions/:region/', handleRegion)
server.get('/regions/:region/:country', handleRegion)
server.get('/regions/:region/:country/:city', handleRegion)    

Upvotes: 1

Related Questions