Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

430
Views
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 answers
Answer question

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 Report

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!