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

118
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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