如何才能在缺失路线上将Express.js变为404?

Hoa*_*Hoa 40 node.js express

目前,我有以下所有其他路线:

app.get('*', function(req, res){
  console.log('404ing');
  res.render('404');
});
Run Code Online (Sandbox Code Playgroud)

根据日志,即使路线在上面匹配,也会被解雇.如何在没有任何匹配的情况下才能让它发射?

Cha*_*les 53

你只需要把它放在所有路线的尽头.

看看传递路径控制的第二个例子:

var express = require('express')
  , app = express.createServer();

var users = [{ name: 'tj' }];

app.all('/user/:id/:op?', function(req, res, next){
  req.user = users[req.params.id];
  if (req.user) {
    next();
  } else {
    next(new Error('cannot find user ' + req.params.id));
  }
});

app.get('/user/:id', function(req, res){
  res.send('viewing ' + req.user.name);
});

app.get('/user/:id/edit', function(req, res){
  res.send('editing ' + req.user.name);
});

app.put('/user/:id', function(req, res){
  res.send('updating ' + req.user.name);
});

app.get('*', function(req, res){
  res.send('what???', 404);
});

app.listen(3000); 
Run Code Online (Sandbox Code Playgroud)

或者,您无能为力,因为所有不匹配的路由都将生成404.然后您可以使用此代码显示正确的模板:

app.error(function(err, req, res, next){
    if (err instanceof NotFound) {
        res.render('404.jade');
    } else {
        next(err);
    }
});
Run Code Online (Sandbox Code Playgroud)

它在错误处理中有记录.

  • 请注意,`app.error()`已在3.x中删除.使用`app.use()`代替传递上面的相同中间件.https://github.com/expressjs/express/wiki/Migrating-from-2.x-to-3.x (7认同)
  • 注意`res.send('what ???',404);`不推荐使用`res.status(404).send('what ???');`代替. (6认同)

Nik*_*ngh 8

您可以在所有路线的末尾处执行此操作,

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')
})
Run Code Online (Sandbox Code Playgroud)


Jus*_*oud 7

我打赌你的浏览器正在跟进对favicon的请求.这就是为什么在请求页面成功200次后,您在日志中看到404.

设置favicon路线.


Tha*_* Ha 6

希望有帮助,我在路线底部使用了这段代码

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();
});
Run Code Online (Sandbox Code Playgroud)