【问题标题】:Passing parameters with express router correctly使用快速路由器正确传递参数
【发布时间】:2021-08-31 08:28:17
【问题描述】:
import express from "express";
const router = express.Router();

router.route("/:category").get(getProductsByCategories);
router.route("/:id").get(getProductDetails);

export default router;

在这段代码中,我添加了两条带参数的路由。但是这段代码没有按预期工作。第一条路线按类别获取产品有效。但第二个没有。有人可以帮我解决此代码的问题吗?

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    问题

    来自 Express 文档 here

    路由参数

    路由参数是使用的命名 URL 段 捕获在 URL 中的位置指定的值。这 捕获的值填充到 req.params 对象中,名称为 路径中指定的路由参数作为它们各自的键。

    路由路径:/users/:userId/books/:bookId

    请求网址:http://localhost:3000/users/34/books/8989

    req.params: { "userId": "34", "bookId": "8989" }

    有了这些信息,我们可以说您的 2 条路线实际上相同。参数的名称不会使它们成为 2 条不同的路线。它改变的只是req.params 对象的填充方式。结果,所有请求都将转到第一个路由。

    建议

    您将需要更改 2 条路线中的 1 条,例如:

    • 要通过ID获取产品,您可以保留它:
    router.route("/:id").get(getProductDetails);
    
    • 要按类别获取产品,您可以更改为:
    router.route("/category/:category").get(getProductsByCategories);
    

    【讨论】:

      【解决方案2】:

      你的路线实际上是同一条路线

      使用查询字符串

      router.route("/").get(getProduct)
      

      在产品功能中

      const {id,category} = req.query
      

      不要忘记在url请求中包含关键字

      {{url}}/product?id=1 // to get detail
      {{url}}/product?category // to get product by category
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-14
        • 1970-01-01
        • 2018-12-26
        • 1970-01-01
        • 2018-09-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多