Categories
Express JavaScript Answers Nodejs

How to render an error message when page is not found with Node.js and Express?

Spread the love

Sometimes, we want to render an error message when page is not found with Node.js and Express.

In this article, we’ll look at how to render an error message when page is not found with Node.js and Express.

How to render an error message when page is not found with Node.js and Express?

To render an error message when page is not found with Node.js and Express, we can add a middleware after all the route middlewares are added.

For instance, we write:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.use((req, res, next) => {
  res.send('not found', 404);
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

We add a route with:

app.get('/', (req, res) => {
  res.send('Hello World!')
})

Then we add:

app.use((req, res, next) => {
  res.send('not found', 404);
});

which returns a 404 error for routes other than /.

We call app.use to add any middleware that are used app-wide.

Conclusion

To render an error message when page is not found with Node.js and Express, we can add a middleware after all the route middlewares are added.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *