Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在express.js中区分路由的路径和参数?_Javascript_Node.js_Typescript_Express - Fatal编程技术网

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

Javascript 如何在express.js中区分路由的路径和参数?,javascript,node.js,typescript,express,Javascript,Node.js,Typescript,Express,我有以下路线的特快申请: // Get category by id innerRouter.get('/:id', categoriesController.getById) // Get all categories along with their subcategories innerRouter.get('/withSubcategories', categoriesController.getAllWithSubcategories) 问题在于express似乎无法区分这两者,例

我有以下路线的特快申请:

// 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
的位置,因为在根路径中有一个匹配的all是不可取的。

我更改了顺序,它工作了,关于将
:id
移动到
category/:id
,这两条路由已经位于
应用程序中。使用('/category',myRouter)
,我只是想简单地休息一下api@TwoHorses-当您使用
/:id
时,您有责任在应用程序内部确保
id
值不会与您使用的其他路径冲突。如果ID是您完全控制的,这可能不难做到,但如果它们是用户定义的类别名称,那么它们很可能会发生冲突。使用
/:id
/somethingElse
作为路由是自找麻烦的,除非您小心地控制id值,以避免与静态路径冲突。@jfriend00那么什么是好的解决方案呢?我只想让我的API尽可能简单possible@TwoHorses-在
/:id
前面使用唯一的路径前缀,该前缀不被其他任何东西使用。我不知道你的应用程序的总体布局和URL结构,因此没有足够的信息知道具体建议什么。URL API设计需要查看您正在做的所有事情的总体布局,以了解如何最好地将每个项目放置到位。