我想在Express/Node服务器上模拟404错误。我该怎么做呢?


当前回答

从Express 4.0开始,有一个专门的sendStatus函数:

res.sendStatus(404);

如果您使用的是Express的早期版本,请使用状态函数。

res.status(404).send('Not found');

其他回答

Express 4.x的更新答案

不同于在旧版本的Express中使用res.send(404),新方法是:

res.sendStatus(404);

Express将发送一个非常基本的404响应,并显示“Not Found”文本:

HTTP/1.1 404 Not Found
X-Powered-By: Express
Vary: Origin
Content-Type: text/plain; charset=utf-8
Content-Length: 9
ETag: W/"9-nR6tc+Z4+i9RpwqTOwvwFw"
Date: Fri, 23 Oct 2015 20:08:19 GMT
Connection: keep-alive

Not Found

在我看来,最好的方法是使用next()函数:

router.get('/', function(req, res, next) {
    var err = new Error('Not found');
    err.status = 404;
    return next(err);
}

然后错误由错误处理程序处理,您可以使用HTML巧妙地设置错误样式。

从Express 4.0开始,有一个专门的sendStatus函数:

res.sendStatus(404);

如果您使用的是Express的早期版本,请使用状态函数。

res.status(404).send('Not found');

你不需要模拟它。我认为res.send的第二个参数是状态码。只需将404传递给该参数。

让我澄清一下:根据expressjs.org上的文档,似乎传递给res.send()的任何数字都将被解释为状态码。所以从技术上讲,你可以:

res.send(404);

编辑:我的错,我说的是res而不是req。它应该在响应时调用

编辑:从Express 4开始,send(status)方法已弃用。如果使用Express 4或更高版本,请使用:res.sendStatus(404)。(感谢@badcc在评论中给出的建议)

在Express站点,定义一个NotFound异常,并在你想要404页面或重定向到/404时抛出它:

function NotFound(msg){
  this.name = 'NotFound';
  Error.call(this, msg);
  Error.captureStackTrace(this, arguments.callee);
}

NotFound.prototype.__proto__ = Error.prototype;

app.get('/404', function(req, res){
  throw new NotFound;
});

app.get('/500', function(req, res){
  throw new Error('keyboard cat!');
});