【发布时间】:2021-06-22 15:33:57
【问题描述】:
通过id查找数据,这样的路由参数
网址是:http://localhost:8000/products/60d1789867bc6624403ade6e
// getting a single product
router.get("/:id", async (req, res, next) => {
const id = req.params.id;
try {
const result = await Product.findById(id);
return res.json({
result,
});
} catch (error) {
return res.status(400).json({
msg: "product not found",
error: error,
});
}
});
但是当我尝试按名称查找时 网址:http://localhost:8000/products/product_name
// getting products by name
router.get("/:name", async (req, res, next) => {
const name = req.params.name;
try {
const result = await Product.find({ name: name });
return res.json({
result,
});
} catch (error) {
return res.status(400).json({
msg: "product not found",
error: error,
});
}
});
这段代码没有执行,url req 转到:id 参数
如何区分
【问题讨论】:
-
制作两个不同的get url,因为express首先获取localhost:8000/products/60d1789867bc6624403ade6e(ID路由)所以它不会进入产品名称路由但是如果你想在路由中获取产品名称然后制作两个不同的获取 localhost:8000/products/id/product_ID 和 localhost:8000/products/name/product_name 等路线