0
0
Expressframework~15 mins

404 Not Found handler in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Express 404 Not Found Handler
📖 Scenario: You are building a simple Express web server. You want to handle requests to pages that do not exist by showing a friendly 404 Not Found message.
🎯 Goal: Create an Express app that responds with a 404 Not Found message for any request that does not match existing routes.
📋 What You'll Learn
Create an Express app instance
Add a basic route for the home page at '/'
Add a 404 handler middleware that catches all unmatched routes
Send a 404 status and a simple text message '404 Not Found' in the 404 handler
💡 Why This Matters
🌍 Real World
Web servers often need to handle requests to pages that do not exist. Showing a clear 404 Not Found message helps users understand the problem.
💼 Career
Knowing how to add middleware and handle 404 errors is a basic skill for backend developers working with Express or similar web frameworks.
Progress0 / 4 steps
1
Create Express app and home route
Write code to import Express, create an app instance called app, and add a GET route for '/' that sends the text 'Home Page'.
Express
Need a hint?

Use express() to create the app. Use app.get for the home route.

2
Add 404 handler middleware
Add a middleware function using app.use that takes req, res, and next parameters. This middleware will handle all unmatched routes.
Express
Need a hint?

Use app.use with three parameters to catch all unmatched routes.

3
Set 404 status and send message
Inside the 404 middleware, set the response status to 404 using res.status(404) and send the text '404 Not Found' using res.send.
Express
Need a hint?

Chain res.status(404) and res.send('404 Not Found') to respond properly.

4
Start the server on port 3000
Add code to start the Express server by calling app.listen on port 3000.
Express
Need a hint?

Use app.listen(3000) to start the server.