How do you send a status code of 404 with a message in Express?

Handling HTTP Status Codes in Express.js

In Express.js, a popular server-side JavaScript framework, you have the ability to handle HTTP requests and responses. An important part of this response handling is dealing with status codes. HTTP status codes are three-digit numbers that represent the status of an HTTP response. They are essential for client-server communication to inform clients, such as web browsers, about the status of the requested resource.

In specific, one of the most commonly used HTTP status codes is 404, which means "Not Found". It's usually sent when the server cannot find the requested resource. In Express.js, there's a specific syntax to send this status code along with a custom message.

The correct way to send a status code of 404 with a custom message in Express.js is res.status(404).send('Not Found'). Let's break it down:

  • res: Represents the response object we use to send back data to the requester.
  • .status(404): A method attached to the res object for setting the HTTP status code.
  • .send('Not Found'): Another method that works on the res object to define a custom message that will be sent along with the status code.

Here is a practical application where you may use this:

app.get('/api/books/:id', (req, res) => {
    let book = database.findBook(req.params.id);
    if (!book)
        res.status(404).send('Not Found');
    else
        res.send(book);
});

In this code snippet, we define a GET endpoint for fetching a book by its ID from our imaginary database. If this book doesn't exist in our database, we send a 404 status code along with a 'Not Found' message. Then, the client receiving this response would know that the book they were looking for is not found.

To conclude, understanding how to work with HTTP status codes in Express.js, especially the 404 status code, is crucial for building reliable and effective APIs. Although there is another syntax for sending responses res.send(404, 'Not Found'), this is considered incorrect because it's outdated and no longer supported in the latest Express.js versions. Always use res.status(404).send('Not Found') to send HTTP status codes and custom messages with responses in Express.js.

Do you find this helpful?