so i've tried to implement a simple search functionality to practice,
my goal is to have the url "/search/(parameter here)" and get the product who's name matches the parameter.
this is my middleware:
router.get('/search/:title', function(req, res, next) {
var title = req.params.title;
Product.find({title: title}, function (err, products) {
if(err) {
res.render('shop/search', {products: null});
}
res.render('shop/search', {products: products});
next();
});
});
i don't know why, but it gives me the error:
Error: Can't set headers after they are sent.
i can't see why i get this, it says i'm changing headers, i'm kind of new to this and i'm not sure where do i change headers?
You cannot call the next middleware ( i.e next()
) after rendering the response to the client, you should remove it, also use return
statement in order to stop the remaining code from executing, here is the correct syntax:
router.get('/search/:title', function(req, res, next) {
var title = req.params.title;
Product.find({title: title}, function (err, products) {
if(err) {
return res.render('shop/search', {products: null});
^^^^^^
}
res.render('shop/search', {products: products});
});
});