13

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?

ismailarilik
  • 2,236
  • 2
  • 26
  • 37

2 Answers2

33

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

Bence Gedai
  • 1,461
  • 2
  • 13
  • 25
2

I’d do only app.use('/course-sessions/', chapterSessionsRouter) and handle the id inside the router.

Jakub Pawlowski
  • 248
  • 1
  • 3
  • 8
  • I think this is the most appropriate solution for now. But it would be good if `app.use` supports route parameters, or `router.use` supports a router as a middleware... – ismailarilik Dec 23 '17 at 10:10