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(‘’);

Updated on: 13-May-2020

805 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements