Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

818
Views
Error [ERR_HTTP_HEADERS_SENT]: no se pueden establecer encabezados después de enviarlos al cliente - Node Express Mongodb

Código novato aquí!

Estoy siguiendo esta guía para configurar un servidor backend usando Node.js, Express y MongoDB - https://www.codementor.io/@olatundegaruba/nodejs-restful-apis-in-10-minutes-q0sgsfhbd

Sigo recibiendo el siguiente error en la terminal cuando uso Postman.

 Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Investigué el hecho de que es posible que deba agregar una declaración de devolución en alguna parte, pero dado que he estado siguiendo la guía, ¿no debería tener este problema?

Aquí está mi archivo de controladores donde creo que puede estar el problema:

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

¡Gracias por adelantado!

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Debe return en sus controladores de errores ( if (err) ). De lo contrario, después de que ocurre el error y res.send(err) envía la respuesta, la ejecución simplemente continúa en la línea después del bloque if e intenta enviar la solicitud nuevamente con res.json() .

Cambio

 if (err) res.end(err)

para

 if (err) return res.send(err)

o para

 if (err) { res.send(err); return; }

Cualquiera de los dos está bien aquí ya que el valor de retorno de la devolución de llamada no se usa para nada.

over 4 years ago · Santiago Trujillo Report

0

Como sugiere este comentario, siempre que intente enviar una respuesta diferente en función de una determinada condición, debe salir del controlador después de enviar la respuesta.

Solo cambia todo tu

if(condition) res.end()

para

if(condition) return res.end() // notice the "return" keyword here

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!