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?
Answer: A is the correct option. By using app. route() method, we can create chainable route handlers for a route path in Express.
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. req. params object is used in this case because it has access to all the parameters passed in the url. app. get('/books/:bookId', (req, res) => { res.
The express. Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests.
The app. route() function returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. Use app. route() to avoid duplicate route names (and thus typo errors). Syntax: app.route( path )
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
I’d do only app.use('/course-sessions/', chapterSessionsRouter) and handle the id inside the router.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With