Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 277
ismailarilik Avatar asked Dec 23 '17 07:12

ismailarilik


People also ask

How can we create Chainable route handlers for a route path in Expressjs app?

Answer: A is the correct option. By using app. route() method, we can create chainable route handlers for a route path in Express.

What is Route parameters 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.

How do you create routes in an Express application?

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.

What is app route in Express?

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 )


2 Answers

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

like image 148
Bence Gedai Avatar answered Sep 19 '22 17:09

Bence Gedai


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

like image 45
Jakub Pawlowski Avatar answered Sep 18 '22 17:09

Jakub Pawlowski