[英]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.