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.
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});
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