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

117
Visualizações
Nodejs: Cannot set headers after they are sent to the

I write this code with NodeJS:

const setOutput = (res, req, data) => {
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify(data));
}

app.post('/getDb', async (req, res, next) => {
    if (!req.body.hasOwnProperty('key')) {
        setOutput(res, req, {
            error: true,
            message: 'You must send key'
        })
    }
    
    const db = openDb(req.body.key);
    
    if (!db) {
        setOutput(res, req, {
            error: true,
            message: 'Not found key'
        })
    }

    setOutput(res, req, {
        error: false,
        message: 'DB create successful',
        data: {
            min: 0.1
        }
    });
})

This code work fine, but I get this error:

(node:253965) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

How can I stop anything after call setOutput?

Note: I don't want use switch or a lot of if else

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Basically, you are trying to call setOutput arrow function multiple times in a request. That is why terminating the execution after sending may help:

if (!req.body.hasOwnProperty('key')) {
        setOutput(res, req, {
            error: true,
            message: 'You must send key'
        })
      return;
    }

const db = openDb(req.body.key);

if (!db) {
    setOutput(res, req, {
        error: true,
        message: 'Not found key'
    })
  return;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

In your request, you're invoking setOutput multiple times which means the request will be sent to the client but the callback function in app.post keeps on executing because you haven't returned anything from app.post's callback you'd invoked the other function which in this case is setOuput so in nodejs world the error simply means that you'd send a response to the client now you can't prepare headers the simple solution would be to return after sending each request like this `

app.post('/getDb', async (req, res, next) => {
    if (!req.body.hasOwnProperty('key')) {
       return setOutput(res, req, {
            error: true,
            message: 'You must send key'
        })
    }
    
    const db = openDb(req.body.key);
    
    if (!db) {
        return setOutput(res, req, {
            error: true,
            message: 'Not found key'
        })
    }

    setOutput(res, req, {
        error: false,
        message: 'DB create successful',
        data: {
            min: 0.1
        }
    });
})

`

about 4 years ago · Juan Pablo Isaza 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