Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

816
Visualizações
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client - Node Express Mongodb

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!

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda