13

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.

Gus Hogg-Blake
  • 2,393
  • 2
  • 21
  • 31

2 Answers2

48

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});
Jason Cust
  • 10,743
  • 2
  • 33
  • 45
-6

Use the Router's mergeParams option to inherit the route params from the parent: http://expressjs.com/4x/api.html#router

Gus Hogg-Blake
  • 2,393
  • 2
  • 21
  • 31
  • Why did you answer your own question with a response from another answer? – Jason Cust Aug 21 '15 at 13:17
  • 8
    I'm glad you found an answer regardless of how you go to it. That is the point of the site but the site only works because people are willing to offer their time to help someone else for no real benefit aside from being given a modicum of credit acknowledging their effort and assistance. I wouldn't say that is "nitpicky". – Jason Cust Aug 22 '15 at 01:16