中间件实现不适用于某些路由

Middleware implementation not working for some routes

在我的项目中,我有 2 个不同的函数用作中间件,它们位于单独目录中的单独文件中,并且我已将它们导入到我的路由文件中。 但是,其中一个函数正确执行,而另一个函数抛出错误

第一个中间件函数(功能正常)是:-

isLoggedIn : function(req,res,next){
        if(req.isAuthenticated()){
            return next();
        }
        res.redirect("/login");
    },

另一个函数(不工作)是:-

checkCampgroundOwnership : function(req,res,next){
        if(req.isAuthenticated()){
                Campground.findById(req.params.id, function(err,foundCamp){
                    if(err){
                        res.redirect("back");
                    }
                    else{
                        if(foundCamp.author.id.equals(req.user._id)){
                            return next();
                        }
                        else{
                            res.redirect("back");
                        }
                    }
                })
            }
            else{
                res.redirect("back");
            }
        }

我在我的路线中实施它们如下:-

router.post("/", middleware.isLoggedIn, function(req,res){
    req.body.description = req.sanitize(req.body.description);
    Campground.create(req.body.camp, function(err,created){
        if(err){
            console.log(err);
        }
        else{
            created.author.id = req.user.id;
            created.author.username = req.user.username;
            created.save();
            res.redirect("/campgrounds");
        }
    })
})

router.put("/:id", middleware.checkCampgroundOwenership, function(req,res){
    Campground.findByIdAndUpdate(req.params.id, req.body.camp, function(err,result){
        if(err){
            console.log(err)
        }
        else{
            res.redirect("/campgrounds/"+ req.params.id);
        }
    })
})

产生的错误如下:-

Error: Route.get() requires a callback function but got a [object Undefined]

问题是什么以及如何解决

您必须声明您的 isLoggedIncheckCampgroundOwnership 如下:

exports.isLoggedIn = (req, res, next) => {
   //your code...
};

所以你可以在你的路由文件中导入。

你打错了:

您输入了:checkCampgroundOwenership

应该是:checkCampgroundOwnership