我有一条路线。
router.post('/add', async (req, res) => {
...
await timeIntervalCheck(req, res);
...
return res.status(200).json({
message: 'Product added'
});
}):
在其中,我调用函数timeIntervalCheck
以下是函数本身:
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'
});
}
}
如果产品的时间适合该周期,则一切正常,但是一旦争端发生或多或少,就会出现错误Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
。
我理解他的意思,因为当仇敌或多或少时,标题已经发送,我继续尝试再次发送。如何确保没有此类错误?如何发送错误更多的错误,而不发出添加产品的错误
答案 0 :(得分:1)
我建议您应该检查timeIntervalCheck
的结果并发送正确的响应。 (或者您可以检查res.headersent
并停止发送两次响应,但是我不喜欢这种方法)
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;
}
}
}