Question about parameters in Routers

I have this api project with a files structure similar to the following:

app.js                /
 |- books
    |- index.js       /books
    |- p-id
       |- index.js    /books/:id

Each index.js file exports an express.Router() that uses the next ‘path extension’ like so:

/* books index.js */
const { Router } = require('express')
const pid = require('./p-id')

const route = () => {
  const router = Router()
  router.get('/', /* GET method */)
  router.use('/:id', pid)
  return router
}

module.exports = route

However when I visit /books/123, req.params is always empty:

/* p-id index.js */
const { Router } = require('express')

const route = () => {
  const router = Router()
  router.get('/', (req, res) => res.json({ params: req.params }))  // req.params == {}
  return router
}

module.exports = route

I came across #3084 which mentioned using Router({ mergeParams: true }). If I do so in p-id index.js my parameters show up. Is the option needed because it is travelling through each router to get to the final route /books/:id and dropping the param at /books along the way? Why are the options only needed at /books/:id and not also at /?

Author: Fantashit

1 thought on “Question about parameters in Routers

  1. Is the option needed because it is travelling through each router to get to the final route /books/:id and dropping the param at /books along the way?

    It’s because the req.params in your function is the params defined just on that route. Each router is independent, and so just because you happened to have some parameters in a parent router doesn’t matter; req.params is cleared out when the request goes into a sub router.

    Why are the options only needed at /books/:id and not also at /?

    This is interesting. Since the / route has no params at all, the req.params is not touched, thus you’re seeing through down to the old params. This kinda smells like a bug, though it’s hard to say if we can realistically fix it at this point in 4.x. We should fix this in 5.0, though.

Comments are closed.