快递中的嵌套路线,其中父路线包含参数 [英] Nested routes in express, where a parent route includes a param

查看:93
本文介绍了快递中的嵌套路线,其中父路线包含参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义路由层次结构的最佳方法是什么,这样我就有一个基本URL /page/:id,然后有了/page/:id/delete/page/:id/edit之类的URL,而不必全部重复/page/:id路径?

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?

我尝试了以下操作,但是id参数在子路径中不可用:

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

我在路由指南中看不到任何有关此行为的信息,但是在这里拥有所有可用的参数似乎很有用,尤其是因为允许在路径的安装路径"中使用这些参数. /p>

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.

首先,您不应将 get 方法用于删除功能.相反,您应该使用 delete 方法.这是两个HTTP快捷方式方法,它们映射到请求中发送的内容. 显示了ExpressJS支持的快捷方式的完整列表,所有这些都可以使用也可以通过路由器.

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.

第二,如果您使用的是 ExpressJS路由器,并且您想保留路径中的参数在安装路由器的位置,需要使用mergeParams选项让ExpressJS知道:

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

这篇关于快递中的嵌套路线,其中父路线包含参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆