node.jsexpress

Why does res.send().status() not send the correct status code?


I'm trying to send some json and a status code like this:

        res.send({message: "ERR"}).status(409)

Why is this sending the wrong status code? Could someone explain the mechanics behind this so I can understand why the status code is not being set?


Solution

  • Swap the functions:

    res.status(409).send({message: "ERR"})
    

    .send() sends the response to the client. .status() sets the status of the response but doesn't send it. (As opposed to .sendStatus() which sets the status and sends it.) You're essentially sending the response first and then trying to update its status afterward.