In my project, I have 2 different functions serving as middleware, which are in a separate file in a separate directory, and I have imported them in my route files. However, one of the functions executes properly while the other throws and error
The first middleware function (which is functioning properly) is :-
isLoggedIn : function(req,res,next){
if(req.isAuthenticated()){
return next();
}
res.redirect("/login");
},
The other function (not working) is :-
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");
}
}
I'm implementing them in my routes as follows :-
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);
}
})
})
The error which is generated is as follows :-
Error: Route.get() requires a callback function but got a [object Undefined]
What is the problem and how to solve it
You have a typo:
You've typed: checkCampgroundOwenership
Should be: checkCampgroundOwnership