The Wayback Machine - https://web.archive.org/web/20231122205042/https://www.geeksforgeeks.org/how-to-add-a-404-error-page-in-the-express/
Open In App
Related Articles

How to add a 404 Error Page in the Express ?

Improve Article
Improve
Save Article
Save
Like Article
Like

Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client’s different incoming requests. In this article, we will discuss how to add a 404 error page i.e not found using the express server. 404 is the status code which means not found in the server.

Installing module: Install the required module using the following command.

npm install express

Project structure: It will look like this.

 

index.js




// Requiring module
const express = require("express")
const app = express()
  
// Handling GET /hello request
app.get("/hello", (req, res, next) => {
    res.send("This is the hello response");
})
  
// Handling non matching request from the client
app.use((req, res, next) => {
    res.status(404).send(
        "<h1>Page not found on the server</h1>")
})
  
// Server setup
app.listen(3000, () => {
    console.log("Server is Running")
})


Run the index.js file using the below command:

node index.js

Output: Now open your browser and go to http://localhost:3000/, the server will respond no page found.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 28 Jun, 2021
Like Article
Save Article
Similar Reads
Related Tutorials