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

前端 未结 4 529
生来不讨喜
生来不讨喜 2020-12-05 09:20

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\');         


        
4条回答
  •  抹茶落季
    2020-12-05 10:04

    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();
    });
    

提交回复
热议问题