我不知道做这件事的函数,有人知道吗?
发布于 2012-03-21 17:45:38
我发现这个例子很有帮助:
https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js
所以,它实际上是这一部分:
// "app.router" positions our routes
// above the middleware defined below,
// this means that Express will attempt
// to match & call routes _before_ continuing
// on, at which point we assume it's a 404 because
// no route has handled the request.
app.use(app.router);
// Since this is the last non-error-handling
// middleware use()d, we assume 404, as nothing else
// responded.
// $ curl http://localhost:3000/notfound
// $ curl http://localhost:3000/notfound -H "Accept: application/json"
// $ curl http://localhost:3000/notfound -H "Accept: text/plain"
app.use(function(req, res, next) {
res.status(404);
// respond with html page
if (req.accepts('html')) {
res.render('404', { url: req.url });
return;
}
// respond with json
if (req.accepts('json')) {
res.json({ error: 'Not found' });
return;
}
// default to plain-text. send()
res.type('txt').send('Not found');
});
发布于 2011-07-04 00:48:33
您可以将中间件放在抛出NotFound
错误的最后位置,
或者甚至直接呈现404页面:
app.use(function(req,res){
res.status(404).render('404.jade');
});
发布于 2013-05-15 14:22:38
以上答案都很好,但其中一半不会返回404作为HTTP状态码,而另一半则不能进行自定义模板呈现。在Expressjs中创建自定义错误页面(404)的最好方法是
app.use(function(req, res, next){
res.status(404).render('404_error_template', {title: "Sorry, page not found"});
});
将此代码放在所有URL映射的末尾。
https://stackoverflow.com/questions/6528876
复制相似问题