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

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

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

0

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

over 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