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

239
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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