How can I get Express.js to 404 only on missing routes?

Viewed 95215

At the moment I have the following which sits below all my other routes:

app.get('*', function(req, res){
  console.log('404ing');
  res.render('404');
});

And according to the logs, it is being fired even when the route is being matched above. How can I get it to only fire when nothing is matched?

7 Answers

Hope it helpful, I used this code in bottom of routes

router.use((req, res, next) => {
    next({
        status: 404,
        message: 'Not Found',
    });
});

router.use((err, req, res, next) => {
    if (err.status === 404) {
        return res.status(400).render('404');
    }

    if (err.status === 500) {
        return res.status(500).render('500');
    }

   next();
});

You can this at the end of all routes,

const express = require('express');
const app = express();
const port = 8080;

// All your routes and middleware here.....

app.use((req, res, next) => {
    res.status(404).json({
        message: 'Ohh you are lost, read the API documentation to find your way back home :)'
    })
})

// Init the server here,
app.listen( port, () => {
    console.log('Sever is up')
})

You can use this

const express = require('express');
const app=express();
app.set('view engine', 'pug');
app.get('/', (req,res,next)=>{
    res.render('home');
});
app.use( (req,res,next)=>{
    res.render('404');
})
app.listen(3000);

Very simple you can add this middleware.

app.use(function (req, res, next) {
//Capture All 404 errors
  res.status(404).render("404.ejs")
})

404 error in a service is typically used to denote that the requested resource is not available. In this article we will see how to handle 404 error in express.

Related