This tutorial shows how to add a 404 (page not found) error page when using ExpressJS routing. If you try to access any path that is not matched to any route then 404 error page should be displayed.
Adding 404 error page
If you have created your project structure using express-generator then you will have separate route folder for keeping route files where you can use express.Router() to create route definitions.
Let's create a separate error HTML too and send that in the case there is no matching route.
views\error.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Error Page</title> </head> <body> <h3>Page not found</h3> </body> </html>
In the app.js file after adding the routes as middleware you can add a separate Express middleware for sending response with status as 404 (not found) and file as the created error.html file.
app.js
const express = require('express'); const app = express(); const port = 3000; const path = require('path'); const usersRouter = require('./routes/users'); const productRouter = require('./routes/products'); // adding routes app.use(usersRouter); app.use(productRouter); // for error page, add after other routes app.use((req, res, next) => { res.status(404).sendFile(path.join(__dirname, 'views', 'error.html')); }) app.listen(port, () => { console.log(`Example app listening on port ${port}`) })
With this if you run app.js and try to access any route which doesn't exist you should get error page as response with status code 404.
That's all for the topic How to Add 404 Error Page in Express.js. If something is missing or you have something to share about the topic please write a comment.
You may also like
- Express Route Parameters - Creating Dynamic URL
- ExpressJS Query Parameters
- ExpressJS res.render() Method With Examples
- Express File Download Using res.download()
- ExpressJS Template Engines Introduction
- Java Static Import With Examples
- JShell in Java
- Java Date Difference Program
- Dispatch Actions From createAsyncThunk - React Example
- Spring Boot + Data JPA + Oracle One to Many Example
No comments:
Post a Comment