首页 > 解决方案 > 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'})
    }
}

标签: javascriptnode.jsexpresssequelize.js

解决方案


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

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

推荐阅读