HTTP status codes

So sometimes, you might want to send something else apart from data, like the status of your response.

Say the response has failed and you want to send back why it failed, so the request was to get a user named XYZ and our server searched and did not find a user named XYZ, the api will send some response that user XYZ was not found and you can attach a HTTP status code 404, which means the something was not found. There are multiple others contexts which you can use. You can refer the image below which has a list of all the HTTP status codes.

Let's see how we can send HTTP status codes in express js, there are two ways, let's see both of them.

Using the send() method

app.get('/', (req, res) => {
    if(userIsAvailable) {
        res.send("Found User")
    } else {
        res.status(404);
        res.send({
            errorMessage: "User not found",
        })
    }
});

Using the sendStatus() method

app.get('/', (req, res) => {
    if(userIsAvailable) {
        res.send("Found User")
    } else {
        res.sendStatus(404);
    }
})

The sendStatus() method is usually used less, because it is just used to send the status code and no additional data with it.

Another way to send the status code, which also happens to be my favourite, this is just chaining methods, so your code is shorter.

app.get('/', (req, res) => {
    if (userIsAvailable) {
        res.send("Found User")
    } else {
        res.status(404).send({
            errorMessage: "User not found",
        });
    }
}); 

Now you may be thinking, this is just a fancy thing of attaching some extra data to your API responses, well they do a lot more than just informing. Imagine that you are accepting/consuming a api and without a error code, you might have to add manual checks where the response was success of failure.

An example showcasing why you need http status codes.

Status Code

This below image from Steve Schoger nicely explains you all the status codes available.

Steve Status Code Sheet

Next Chapter

Dynamic Routes