javascript - express和sequelize中同一路由上的多个get方法冲突
问题描述
我构建了简单的产品crud,所以当我向 http://localhost:4000/products?name=pen 申请时,我有一条通过 id 搜索产品和其他按名称搜索产品的路线,路线发生冲突并且不要按名称退回产品。
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);
推荐阅读
- java - 特殊字符“”在Linux中不起作用,转换为“?”
- c# - ASP.NET Core -- 上传 .json 文件并转换为 List
- python - 如何使用 Python 比较两个矩阵的相似性?
- python - Python:按多列熊猫分组
- ios - “使用未解析的标识符” 无法为我的生活弄清楚发生了什么。(Xcode,斯威夫特)
- python - 是否可以基于某些列查找从 CSV 文件中读取数据,而无需将整个文件读入内存?
- flutter - NotifyListeners() 在 Flutter 中不能正常工作
- javascript - 使用制表符创建页面持久性
- c# - Release模式下的程序集反射问题
- java - java中的Haskell,我如何在java中实现“any”(haskell)?