Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

241
Vistas
Can`t set headers after they are sent

I`m trying to find an error in my code, and nothing from other topics fits.

There is app.js code, which contains get method from Express module:

app.get('/notes', notesController.all);

There is notesController.js code, which exports to app.js create method:

exports.all = function (req, res) {
    Notes.all(function(err, docs){
        if(err){
            console.log(err);
            return res.sendStatus(500);
        }
        res.send(docs);
    })
};

In model this code:

exports.all = function (cb) {
    db.get().collection('notes').find().toArray(function (err, docs) {
        cb(err,docs);
    })
};

App crashes with this error:

process.nextTick(function() { throw err; });
                              ^

Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11) at ServerResponse.header (O:\OGPI6\node_modules\express\lib\response.js:725:10) at ServerResponse.json (O:\OGPI6\node_modules\express\lib\response.js:253:10) at ServerResponse.send (O:\OGPI6\node_modules\express\lib\response.js:158:21) at O:\OGPI6\controllers\notes.js:9:13 at O:\OGPI6\models\notes.js:6:9 at handleCallback (O:\OGPI6\node_modules\mongodb\lib\utils.js:120:56) at O:\OGPI6\node_modules\mongodb\lib\cursor.js:860:16 at handleCallback (O:\OGPI6\node_modules\mongodb-core\lib\cursor.js:171:5) at setCursorDeadAndNotified (O:\OGPI6\node_modules\mongodb-core\lib\cursor.js:505:3)

At my mind only error with "controller" in the callback function:

if(err){
            console.log(err);
            return res.sendStatus(500);
        }
        res.send(docs);

But I thought that when an error occurs it must terminate function and return sendStatus(500), but after logging an error in the console it tries to return res.send(docs) and then the app crashes because it is sending the second header. It looks fine but doesn`t work. Can anyone point which way I have failed?

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Use the "next" parameter in the middleware to make express know that the purpose of this middleware is completed and there is no further need to execute the code.

exports.all = function (req, res, next) {
    Notes.all(function(err, docs){
        if(err){
            console.log(err);
            res.sendStatus(500);
            return next();
        }
        res.send(docs);
    })
};

Execution of code after return maybe due to the async nature.

You can also use else block.

exports.all = function (req, res, next) {
        Notes.all(function(err, docs){
            if(err){
                console.log(err);
                res.sendStatus(500);

            }
            else res.send(docs);
        })
    };
about 4 years ago · Santiago Trujillo Denunciar

0

Change the code to

if(err){
  console.log(err);
  return res.status(500).send(err);
}
res.send(docs);
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda