Reputation: 96
I was under the impression that res.send() ends the request-response cycle, but without return
in the else block, next(ex)
is called which passes the response object to error handling middleware, resulting in Error: Can't set headers after they are sent.
Where is my understanding off? I am using express-async-errors
to catch errors, if that's important.
router.get('/', async (req, res, next) => {
// get all staff sorted by name
const allStaff = await Staff.find().sort('name');
if (!allStaff) {
res.status(404).send('No staff');
} else {
return res.status(200).send(allStaff);
}
next(ex);
});
Upvotes: 0
Views: 134
Reputation: 256
In your question, you mention it yourselves that the next() function passes the response object to the error handling middleware, so the the next middleware will execute even if you dont want it to i.e allstaff would be sent succesfully but then the next() function would be invoked.
What you are doing (without return in the else block):
Sending the allstaff object and hence trying to end the request response cycle , but then calling next() hence calling the next middleware which tries to mess up with what would otherwise have been a successful request response cycle.
router.get('/', async (req, res, next) => {
// get all staff sorted by name
const allStaff = await Staff.find().sort('name');
if (!allStaff) {
res.status(404).send('No staff');
} else {
res.status(200).send(allStaff); //send the response..expect the req-res cycle to end
}
next(ex); //then call next which might try to hamper the outgoing response
});
What you should do instead:
If you send the response then in no way should it encounter other statement which tries to send the response again, I prefer the folloing code personally:
router.get('/', (req, res, next) => {
// get all staff sorted by name
Staff.find().sort('name').exec(function (err, docs) { //this callback function will handle results
if (err) {
next(); //if there is an error..then the next middleware will end the req response cycle
} else {
if (docs.length == 0) {
res.status(404).send('No staff'); //send response,the req- res cycle ends,never disturbed again...story finished
} else {
res.status(200).send(docs); //send response,the req- res cycle ends,never disturbed again.....story finished
}
}
});
});
Upvotes: 1