- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Adding 404 page in express
Now we have a App.js and route.js for handling routes. For any other http requests for which we have not added any request handling will results into an error page. Example for url ‘test’ −
App.js
const http = require('http'); const express = require('express'); const bodyParser = require('body-parser'); const route = require('./routes'); const app = express(); app.use(bodyParser.urlencoded({extended: false})); app.use(route); const server = http.createServer(app); server.listen(3000);
Showing meaningful error message on incorrect url’s−
We can add a all catch middleware for incorrect url at the end of all middleware’s in App.js −
const http = require('http'); const express = require('express'); const bodyParser = require('body-parser'); const route = require('./routes'); const app = express(); app.use(bodyParser.urlencoded({extended: false})); app.use(route); app.use((req, res,next)= >{ res.send('<h1> Page not found </h1>'); }); const server = http.createServer(app); server.listen(3000);
The last middleware is a request handler if no request handler is found and returns a response. From this all catch middleware we can send message for incorrect paths.
Now for any incorrect path we see below output on browser −
We can use separate router from express and add it in the last by order respective other routers.
Sending 404 status code −
app.use((req, res,next)=>{ res.status(404).send('<h1> Page not found </h1>'); });
We can chain other functions like setHeader in the response before sending actual message.
res.setHeader(‘’).send(‘’);
- Related Articles
- Adding a Page break/new page in SAP Script
- Adding middleware in Express in Node.js
- Adding YouTube videos on an HTML web page
- What soft 404 errors are and how they differ from regular 404 errors
- How to check URL for 404 using Selenium WebDriver?
- Find the HCF and LCM of 96 and 404?
- How to make page links in HTML Page?
- The Negative Impact of 404 Errors on SEO and User Experience
- Adding Time in Python
- Usage of page-break-before, page-break-after, and page-break-inside properties in CSS
- Adding two Sets in Javascript
- Adding a DeleteView in Django
- Adding 3D Objects in Flutter
- Page Faults in LFU
- Page Faults in LRU
