Express 中的嵌套路由,其中​​父路由包含参数

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

定义路由层次结构的最佳方法是什么,这样我就有了 /page/:id 的基本 URL,然后是像 /page/:id/delete/page/:id/edit 这样的 url,而没有必须在所有路径中重复 /page/:id 位?

我尝试了以下方法,但是 id 参数在子路由中不可用:

pageActions = express.Router!

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

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

我在路由指南中看不到任何提及此行为的信息,但在这里提供所有参数似乎很有用,特别是因为在路由的 "mount path" 中包含参数是允许。

有两件事我相信你可能会感到困惑。

首先,你不应该使用 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 显示了 ExpressJS 支持的快捷方式的完整列表,这些都可以被路由器使用。

其次,如果你正在使用 ExpressJS Router 并且你想保留你安装路由器的路径中的参数,你需要让 ExpressJS 知道使用 mergeParams 选项:

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

使用路由器的 mergeParams 选项从父级继承路由参数:http://expressjs.com/4x/api.html#router