繁体   English   中英

如何区分 express.js 中路由的路径和参数?

[英]How to distinguish paths and params of routes in express.js?

我有一个包含以下路线的快速申请:

// Get category by id
innerRouter.get('/:id', categoriesController.getById)

// Get all categories along with their subcategories
innerRouter.get('/withSubcategories', categoriesController.getAllWithSubcategories)

问题是 express 似乎没有区分两者,例如这个请求:

http://localhost:3000/api/categories/withSubcategories

Express 实际上会调用categoriesController.getById而不是categoriesController.getAllWithSubcategories

我知道我可以创建一条路线,然后检查req.params.id ,但我想相信有一种更优雅的方式来做到这一点,是吗?

Express 对您定义路由的顺序很敏感,因此将/withSubcategories /:id上方将解决问题。 但是,您可能应该将/:id移动到/category/:id之类的位置,因为不建议在根路径中使用 match-all。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM