Home > Back-end >  Why does app.put always return status code 200 when res.status(400)
Why does app.put always return status code 200 when res.status(400)

Time:05-29

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

CodePudding user response:

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)

CodePudding user response:

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

  • Related