node.jsexpressurl-routing

Nested routes in express, where a parent route includes a param


What is the best way of defining a route hierarchy so that I have a basic URL of /page/:id, and then urls like /page/:id/delete and /page/:id/edit, without having to repeat the /page/:id bit in all the paths?

I've tried the following, but the id param isn't available in the sub routes:

pageActions = express.Router!

pageActions.get "/delete", (request, response) ->
    request.params.id #undefined

app.use "/page/:id", pageActions

I can't see any mention of this behaviour in the routing guide, but it seems like it would be useful to have all of the params available here, especially since having params in the route's "mount path" is allowed.


Solution

  • There are two things I believe you might be confused about.

    First, you shouldn't be using the get method for delete functions. Instead, you should be using the delete method. These are two of the HTTP shortcut methods that are mapped to what is sent in the request. This shows the full list of the shortcuts that are supported by ExpressJS and these all can be used by a router as well.

    Second, if you are using a ExpressJS Router and you want to preserve parameters from the path where you are mounting the router you need to let ExpressJS know that with the mergeParams option:

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