Reputation: 2371
In my Nodejs code for Mongoose, I've got a create
function that used to work just fine, but something has happened where when the function is invoked, it fires and the request is made, but I get this error:
Here is the error in my terminal:
PUT /api/request/create 200 98.981 ms - 1929
events.js:160
throw er; // Unhandled 'error' event
^
Error: Can't set headers after they are sent.
Here is my function:
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();
});
}
I have other places in my app that utilize almost identical code and they don't have any issue. Is there some kind of race condition that's happening that I'm not accounting for here?
Upvotes: 3
Views: 1667
Reputation: 1322
If err
is true
, then your code will respond with the status 401 and then again trying to respond with status 200. So try
if (err) {
res.status(401).json({
message: err
});
console.log(err);
}
// Add else
else{
res.status(200).json({
request
});
}
Upvotes: 1