Search code examples
expressrouteparams

Use route parameters with `app.use` on Express


I cannot use route parameters with app.use on Express 4.16.2.

I have a statement like this:

app.use('/course-sessions/:courseSessionId/chapter-sessions', chapterSessionsRouter)

And, in chapter sessions router:

// Index.
router.get('/', ...resource.indexMethods)

When I got '/course-sessions/0/chapter-sessions/', I have 404.

Then I am trying a statement like this:

app.get('/course-sessions/:courseSessionId/chapter-sessions', ...chapterSessionResource.indexMethods)

Now I have the result I want. So route parameters don't work with app.use.

While I am researching, I got this GitHub issue and this pull request which closes the issue. But it seems that the issue is still around here. Or do I make something wrong?


Solution

  • You have to setup your router in a different way, try using mergeParams to access parameters in parent routes.

    let router = express.Router({ mergeParams: true });
    

    See docs: http://expressjs.com/en/api.html