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

431
Vistas
Why does app.put always return status code 200 when res.status(400)

I have this piece of code:

app.put("/:id", async (req, res) => {
    let id = req.params.id;

    // validate id
    if(id < 0 || isNaN(id)) {res.send(Helper.ID_ERROR).status(400); return;}

    // check if id exists
    let sensorValueById = await sensorValue.getById(id);
    if (sensorValueById.length == 0) {
        res.send(Helper.NOTHING_FOUND_ERROR).status(404);
        return;
    }

    let sensorValueBody = req.body;
    if (!checkProperties(properties, sensorValueBody)) {
        res.send(Helper.INVALID_PROPERTIES_ERROR).status(400);
        return;
    }

    sensorValueBody.id = id;
    res.send(await sensorValue.update(sensorValueBody));
})

When I access this route and make a mistake on purposes I get the correct message: Id must be number and positive!, but the status code is 200 and not 400

Same for the 2 error responses below it always returns 200 as status code but the right message.

When I use sendStatus instead of status I get this error:

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

I understand what it means but I don't know why it sends some other header before it, and I don't know where it sends it before

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

0

Firstly; Errors in Node.js are handled through exceptions. An exception is created using the throw keyword.

See here for more information. Error handling in Node.js

The res object represents the HTTP response that an Express app sends when it gets an HTTP request.

res.send([body]) Sends the HTTP response.

res.status(code) Sets the HTTP status for the response.

See here for more information about express response.

Your answer here:

res.status(400).send(Helper.ID_ERROR)
res.status(404).send(Helper.NOTHING_FOUND_ERROR)
res.status(400).send(Helper.INVALID_PROPERTIES_ERROR)
over 4 years ago · Santiago Trujillo Denunciar

0

Just call .status(XXX) before .send({}) on the Reply object

over 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