【问题标题】:How to distinguish paths and params of routes in express.js?如何区分 express.js 中路由的路径和参数?
【发布时间】:2020-05-22 20:16:10
【问题描述】:

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

// 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,但我想相信有更优雅的方法可以做到这一点,是吗?

【问题讨论】:

    标签: javascript node.js typescript express


    【解决方案1】:

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

    【讨论】:

    • 我更改了顺序,它起作用了,关于将:id 移动到category/:id,这两条路线已经位于app.use('/category', myRouter) 中,我只是想让它成为一个简单的 REST api跨度>
    • @TwoHorses - 当您使用/:id 时,您有责任在应用程序内部确保没有id 值与您使用的其他路径发生冲突。如果 id 是您完全控制的东西,那可能并不难做到,但如果它们是,例如,用户定义的类别名称,那么它们很可能会发生冲突。使用 /:id/somethingElse 作为路由是自找麻烦,除非您仔细控制 id 值以免与静态路径发生冲突。
    • @jfriend00 那么什么是好的解决方案?我只想让我的 API 尽可能简单
    • @TwoHorses - 在 /:id 前面使用唯一的路径前缀,其他任何东西都不会使用它。我不知道您的应用程序的整体布局和 URL 结构是否有足够的信息来知道具体建议什么。 URL API 设计需要了解您所做的一切的整体布局,以了解如何最好地放置每个项目。
    猜你喜欢
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 2012-04-18
    相关资源
    最近更新 更多