Code newbie here!
I'm following this guide to set up a backend server using Node.js, Express and MongoDB - https://www.codementor.io/@olatundegaruba/nodejs-restful-apis-in-10-minutes-q0sgsfhbd
I keep receiving the following error in the terminal when using Postman.
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I looked into the fact I may need to add a return statement somewhere, but since I've been following the guide, I shouldn't be having this issue?
Here's my controllers file where I think the problem may be:
'use strict';
var mongoose = require('mongoose'),
Task = mongoose.model('Tasks');
exports.listAllTasks = function (req, res) {
Task.find({}, function (err, task) {
if (err) res.send(err);
res.json(task);
});
};
exports.createATask = function (req, res) {
var newTask = new Task(req.body);
newTask.save(function (err, task) {
if (err);
res.send(err);
res.json(task);
});
};
exports.readATask = function (req, res) {
Task.findById(req.params.taskId, function (err, task) {
if (err) res.send(err);
res.json(task);
});
};
exports.updateATask = function (req, res) {
Task.findOneAndUpdate(
{ _id: req.params.taskId },
req.body,
{ new: true },
function (err, task) {
if (err) res.send(err);
res.json(task);
}
);
};
exports.deleteATask = function (req, res) {
Task.deleteMany(
{
_id: req.params.taskId,
},
function (err, task) {
if (err) res.send(err);
res.json({ message: 'Task successfully deleted' });
}
);
};
Thanks in advance!
You need to return in your error handlers (if (err)). Otherwise after the error occurs and res.send(err) sends the response, execution just continues on the line after the if block and it tries to send the request again with res.json().
Change
if (err) res.end(err)
to
if (err) return res.send(err)
or to
if (err) {
res.send(err);
return;
}
Either one is okay here as the return value of the callback isn't used for anything.
As this comment suggests, whenever you are trying to send a different response based on a certain condition, you must exit the controller after sending the response.
Just change all your
if(condition) res.end()
to
if(condition) return res.end() // notice the "return" keyword here