gpt4 book ai didi

node.js - Node/ Mongoose - 错误 : Can't set headers after they are sent

转载 作者:可可西里 更新时间:2023-11-01 09:48:18 26 4
gpt4 key购买 nike

在我的 Mongoose Nodejs 代码中,我有一个 create 函数,它过去工作得很好,但是在调用该函数时发生了一些事情,它会触发并发出请求,但我收到此错误:

这是我的终端中的错误:

PUT /api/request/create 200 98.981 ms - 1929
events.js:160
throw er; // Unhandled 'error' event
^

错误:发送后无法设置 header 。

这是我的功能:

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();
});
}

我的应用程序中还有其他地方使用几乎相同的代码,它们没有任何问题。是否存在某种我在这里没有考虑的竞争条件?

最佳答案

如果 errtrue,那么您的代码将以状态 401 响应,然后再次尝试以状态 200 响应。所以尝试

 if (err) {
res.status(401).json({
message: err
});
console.log(err);
}
// Add else
else{

res.status(200).json({
request
});
}

关于node.js - Node/ Mongoose - 错误 : Can't set headers after they are sent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44853812/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com