Reputation: 1033
I'm working with node+express+MongoDB.
I dont understand this error. When I comment next() it's fine and works but when I use next() I'm getting the error:
Error: Can't set headers after they are sent.
videos.route('/')
.get(function(req, res, next) {
Video.find({},function (err,videosCollection) {
if (err)
{
console.log(err);
}
if(!videosCollection.length)
{
console.log("Videos not found");
}
else
{
console.log("videos found");
res.status(200).json(videosCollection);
}
})
// next();
})
Upvotes: 0
Views: 1341
Reputation: 5097
When you call the next function it will call the following middleware after this route.
You are calling this function before the callback is called in Video.find. If you want to call next, you have to do it inside the callback as below.
videos.route('/')
.get(function(req, res, next) {
Video.find({},function (err,videosCollection) {
if (err)
{
console.log(err);
}
if(!videosCollection.length)
{
console.log("Videos not found");
}
else
{
console.log("videos found");
res.status(200).json(videosCollection);
}
next()
})
})
Upvotes: 1
Reputation: 2256
next()
in express passes async control to the next middlewear in the chain.
This is how next
should be used. To pass errors down the chain of middleware.
videos.route('/')
.get(function(req, res, next) {
Video.find({},function (err,videosCollection) {
if (err){
console.log(err);
// pass the error along
next(err);
}else if(!videosCollection.length){
// pass a new error along
next(new Error("Videos noz found"));
}else{
console.log("videos found");
// no need to call next
// res.json finishes the connection
res.status(200).json(videosCollection);
}
})
})
Upvotes: 1
Reputation: 3778
When you use res.status or res.send the request has ended and the function does a soft return. When you do next() you're passing it along in the chain of middleware and endpoints. So basicly, you'll do double return.
So the message tells you that you cant return a response after the response has been returned to the client.
Only when you're writing middleware do you need to use next.
Upvotes: 1