为什么节点js不能在类似的路由上工作?

时间:2015-08-05 13:25:15

标签: javascript node.js express

如果我将获取搜索路径放在顶部,那么一切正常,如果我将搜索路径放在最后,那么它就不会工作,Node继续调用以ID作为参数的路由,为什么会发生这种情况,什么是它的解决方案?

router.get('/search', function (req, res) {

    var p_Where = {};

    if (req.query.IsDeleted)
        p_Where.IsDeleted = req.query.IsDeleted;

    if (req.query.CustomerName)
        p_Where.CustomerName = { $like: '%' + req.query.CustomerName + '%' };

    if (req.query.PhoneNumber)
        p_Where.PhoneNumber = { $like: '%' + req.query.PhoneNumber + '%' };

    if (req.query.OmitCustomerID)
        p_Where.CustomerID = { $ne: req.query.OmitCustomerID };

    if (req.query.CustomerID)
        p_Where.CustomerID = req.query.CustomerID;

    if (req.query.ShowAutoGenerated)
        p_Where.IsAutoGenerated = req.query.ShowAutoGenerated;

    if (req.query.DeviceNumber)
        p_Where.DeviceNumber = req.query.DeviceNumber;

    if (req.query.CarrierID)
        p_Where.CarrierID = req.query.CarrierID;

    console.log(p_Where);
    models.Product.findAll ({
        where : p_Where,
    }).then(function (customer) {
        res.json({
            status : true,
            message : "Products has been found",
            data : customer
        });
    });
});




router.get ('/', function (req, res) {

    models.Product.findAll ({
        where: {
            WholeSaleCustomerId: req.get ("wscId")
        },
        include: [models.ProductSpecification]
    }).then (function (Product) {

        if (Product.length == 0) {
            res.status (404).json ({
                status: false,
                message: "No product has been found."
            });
        }else{
            res.json ({
                status: true,
                message: "Products has been found.",
                data: Product
            });
        }

    });

});



router.get ('/:productId', function (req, res) {
    models.Product.findOne({
        where: {
            WholeSaleCustomerId: req.get ("wscId"),
            id: req.params.productId
        },
        include: [models.ProductSpecification]
    }).then (function (Product) {
        if (!Product) {
            res.status (404).json ({
                status : false,
                message : "No product has been found."
            });
            return;
        }else{
            res.json ({
                status : true,
                message : "Product has been found.",
                data : Product
            });
        }

    });
});

2 个答案:

答案 0 :(得分:1)

这是因为/search匹配/:productId。路线按顺序检查,而不是与您声明的整套路线的匹配程度。

解决方案是您已经使用的解决方案:在/search之前声明/:productId(有一些方法可以解决这个问题,但它们很糟糕)。

答案 1 :(得分:0)

这会中断,因为Node识别第一个匹配的路由并且/匹配它们。您应该为您的路线提供更详细的名称,例如/ all和/ productById /:id