Reputation: 948
I have a route.
router.post('/add', async (req, res) => {
...
await timeIntervalCheck(req, res);
...
return res.status(200).json({
message: 'Product added'
});
}):
In it, I call the function timeIntervalCheck
Here is the function itself:
function timeIntervalCheck(req, res) {
let end_date = req.body.end_date;
let starting_date = req.body.starting_date;
let date = moment(end_date).diff(moment(starting_date), 'hours');
if (date < 2 || date > 168) {
return res.status(422).json({
err: 'The product cannot be published for less than 2 hours and longer than 7 days'
});
}
}
If the time of the product fits into the period everything works well, but as soon as the periud is less or more then an error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
.
I understand him for what it is, because the headings are already sent when the periud is more or less and I continue to try to send them again. How can I make sure that there is no such error? How to send an error that periud more and not to issue that the product is added
Upvotes: 0
Views: 32
Reputation: 880
I suggest you should check the result from timeIntervalCheck
and send the proper response. (or you can check res.headersent
and stop sending the response twice, but i don't prefer this method)
router.post('/add', async (req, res) => {
...
let checkResult = timeIntervalCheck(req); // please note that only async function requires await flag
...
if (checkResult === true) {
return res.status(200).json({
message: 'Product added'
});
} else {
return res.status(422).json({
err: 'The product cannot be published for less than 2 hours and longer than 7 days'
});
}
}):
--
function timeIntervalCheck(req, res) {
let end_date = req.body.end_date;
let starting_date = req.body.starting_date;
let date = moment(end_date).diff(moment(starting_date), 'hours');
if (date < 2 || date > 168) {
return false;
} else {
return true;
}
}
}
Upvotes: 1