How to catch page not found in express router

I would like to catch 404 page not found error in express router.

I use a basic example :

const express = require('express');

const app = express();

const router = express.Router();

// ROUTER MID BEFORE
router.use((req, res, next) => {console.log("Router Mid => Before"); next();});

// ROUTER PAGE /BAR
router.get('/bar', (req, res, next) => {
 console.log("Router page '/bar'");
 res.send('<body><h1>Hello World</h1></body>');
 next();
 }); 

// ROUTER NOT FOUND
router.get('*', (req, res, next) => {console.log("Router NOT FOUND"); next();});

// ROUTER MID AFTER
router.use((req, res, next) => {console.log("Router Mid => After"); next();});

// APP MID BEFORE
app.use((req, res, next) => {console.log("----"); console.log("App Mid => Before"); next();});

app.use('/foo', router);

// APP NOT FOUND
app.get('*', (req, res, next) => {console.log("App NOT FOUND"); next();});

// APP MID AFTER
app.use((req, res, next) => {console.log("App Mid => After"); console.log("----"); next();});

app.listen(3000, () => {console.log("App Listenning")});

I expect the following result :

Request on /anything

----
App Mid => Before
App NOT FOUND
App Mid => After
----

Request on /foo/anything

----
App Mid => Before
Router Mid => Before
Router NOT FOUND
Router Mid => After
App Mid => After
----

Request on /foo/bar

----
App Mid => Before
Router Mid => Before
Router page '/bar'
Router Mid => After
App Mid => After
----

But the Not Found page are executed on every requests

For example a Request /foo/bar gives me :

----
App Mid => Before
Router Mid => Before
Router page '/bar'
Router NOT FOUND
Router Mid => After
App NOT FOUND
App Mid => After
----

How can I achieve that ?

27 thoughts on “How to catch page not found in express router”

  1. 242397 457626excellent issues altogether, you simply gained a new reader. What could you recommend about your post which you created some days within the past? Any positive? 528965

    Reply

Leave a Comment