gpt4 book ai didi

javascript - 同一路由上的多个 get 方法在 express 和 sequelize 中发生冲突

转载 作者:行者123 更新时间:2023-12-03 22:22:57 24 4
gpt4 key购买 nike

我构建了简单的产品 crud,所以我有一个通过 id 搜索产品的路线,其他通过名称搜索产品的路线,当我向 http://localhost:4000/products?name=pen 提出请求时,路线发生冲突并且不要按名称退回产品。

router.get('/products/:id', ProductController.getProductById);
router.get('/products/:name', ProductController.getProductByName);
和你的尊重功能
const getProductById = async (req, res) =>{
try{
const { id } = req.params;
const product = await Product.findByPk(id);
if(product){
return res.status(200).json({ product });
}
return res.status(404).send('Product With ID does exist');
}catch (err){
return res.status(500).send({ error : 'Error on select by id'})
}
}

const getProductByName = async (req, res) =>{
try{
const name = req.query.name;
const product = await Product.findAll({
where: { name: name}
});
if(product){
return res.status(200).json({ product });
}
return res.status(404).send('Product With Name does exist');
}catch (err){
return res.status(500).send({ error : 'Error on select by id'})
}
}

最佳答案

如果您使用查询参数,则不应在路由路径中指明它们:

router.get('/products', ProductController.getProductByName); 

关于javascript - 同一路由上的多个 get 方法在 express 和 sequelize 中发生冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67570245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com