如何将 404 错误重定向到 ExpressJS 中的页面? [英] How to redirect 404 errors to a page in ExpressJS?
本文介绍了如何将 404 错误重定向到 ExpressJS 中的页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道这样做的函数,有人知道吗?
I don't know a function for doing this, does anyone know of one?
推荐答案
我发现这个例子很有帮助:
I found this example quite helpful:
https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js
所以,实际上是这部分:
So, it is actually this part:
// "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');
});
这篇关于如何将 404 错误重定向到 ExpressJS 中的页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文