Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Redirect 404 errors to a page in Express.js ?

  • Last Updated : 10 Oct, 2021

Express Js is a web application framework based on Node.js web server functionality that helps us to create web servers with lesser complexity and in a well-organized manner. Express provides routing services that help us in creating application endpoints that respond based on the HTTP request method (GET, POST, DELETE, etc) and the requested route.

In Express if we want to redirect the user to the 404 error page if a particular route does not exist then we can use the app.all() method as the last route handler method and * (asterisk) as the route name. Asterisk is a wildcard that matches any route name.

Syntax:

app.all('*', (req, res) => {
    // code logic
})

The route mentioned above can handle all kinds of HTTP request methods and request to any route name.

 

Project Setup

Step 1: Install Node.js if you haven’t already.

Step 2: Create a folder for your project and cd (change directory) into it. Create a new file named app.js inside that folder. Now, initialize a new Node.js project with default configurations using the following command.

npm init -y

Step 3: Now install express inside your project using the following command on the command line.

npm install express

Project Structure: After following the steps your project structure will look like the following.

app.js




const express = require('express');
const app = express();
  
app.get('/', (req, res) => {
  res.send('<h1>Home page</h1>');
});
  
app.get('/products', (req, res) => {
  res.send('<h1>Products page</h1>');
});
  
// This route will handle all the requests that are 
// not handled by any other route handler. In 
// this hanlder we will redirect the user to 
// an error page with NOT FOUND message and status
// code as 404 (HTTP status code for NOT found)
app.all('*', (req, res) => {
  res.status(404).send('<h1>404! Page not found</h1>');
});
  
app.listen(3000, () => {
  console.log('Server is up on port 3000');
});


Step to run the application: You can run your express server by using the following command on the command line.

node app.js

Output: Open the browser and go to http://localhost:3000, and manually switch to http://localhost:3000/some_invalid_route and you will be redirected to our error page with a message.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!