在我的Mongoose的Nodejs代码中,我有一个create
函数,以前工作得很好,但是在调用函数的时候发生了一些事情,它会触发并发出请求,但是我得到了这个错误:
这是终端中的错误:
PUT /api/request/create 200 98.981 ms - 1929
events.js:160
throw er; // Unhandled 'error' event
^
错误:发送后无法设置标头。
这是我的功能:
exports.create = (req, res, next) => {
const body = req.body;
const Request = new Requests({
//customer_id: body.customer_id,
customer: body.customer,
tasks: body.tasks,
submitted_by: body.submitted_by,
assignees: body.assignees,
// safety_equipment: body.safety_equipment,
special_instructions: body.special_instructions,
area_instructions: body.area_instructions,
additional_equipment: body.additional_equipment,
access: body.access,
training: body.training,
ppe: body.ppe,
description: body.description,
square_footage: body.square_footage,
flooring_type: body.flooring_type,
due_date: body.due_date,
is_converted: body.is_converted,
quote_amount: body.quote_amount,
is_billable: body.is_billable,
budgeted_time: body.budgeted_time,
site_visit: body.site_visit,
locations: body.locations,
job_number: body.job_number
});
Request.save( (err, request) => {
if (err) {
res.status(401).json({
message: err
});
console.log(err);
}
res.status(200).json({
request
});
return next();
});
}
我的应用中有其他地方使用几乎完全相同的代码而且没有任何问题。是否有某种竞争条件正在发生,我不在这里考虑?
答案 0 :(得分:1)
如果err
为true
,那么您的代码将以状态401回复,然后再次尝试以状态200回复。请尝试
if (err) {
res.status(401).json({
message: err
});
console.log(err);
}
// Add else
else{
res.status(200).json({
request
});
}