node.js 如何将 404 错误重定向到 ExpressJS 中的页面?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6528876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to redirect 404 errors to a page in ExpressJS?
提问by Felix
I don't know a function for doing this, does anyone know of one?
我不知道这样做的功能,有人知道吗?
回答by Felix
I found this example quite helpful:
我发现这个例子很有帮助:
https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js
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.send({ error: 'Not found' });
return;
}
// default to plain-text. send()
res.type('txt').send('Not found');
});
回答by Alfred
I think you should first define all your routes and as the last route add
我认为您应该首先定义所有路线,并作为最后一条路线添加
//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
res.status(404).send('what???');
});
An example app which does work:
一个可以工作的示例应用程序:
app.js:
应用程序.js:
var express = require('express'),
app = express.createServer();
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.send('hello world');
});
//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
res.send('what???', 404);
});
app.listen(3000, '127.0.0.1');
alfred@alfred-laptop:~/node/stackoverflow/6528876$ mkdir public
alfred@alfred-laptop:~/node/stackoverflow/6528876$ find .
alfred@alfred-laptop:~/node/stackoverflow/6528876$ echo "I don't find a function for that... Anyone knows?" > public/README.txt
alfred@alfred-laptop:~/node/stackoverflow/6528876$ cat public/README.txt
.
./app.js
./public
./public/README.txt
alfred@alfred-laptop:~/node/stackoverflow/6528876$ curl http://localhost:3000/
hello world
alfred@alfred-laptop:~/node/stackoverflow/6528876$ curl http://localhost:3000/README.txt
I don't find a function for that... Anyone knows?
回答by Ganesh Kumar
You can put a middleware at the last position that throws a NotFounderror,
or even renders the 404 page directly:
可以在最后抛出NotFound错误的位置放一个中间件,
甚至直接渲染404页面:
app.use(function(req,res){
res.status(404).render('404.jade');
});
回答by Sushant Gupta
The above answers are good, but in half of these you won't be getting 404 as your HTTP status code returned and in other half, you won't be able to have a custom template render. The best way to have a custom error page (404's) in Expressjs is
上面的答案很好,但在其中一半中,您将不会在返回 HTTP 状态代码时收到 404,而在另一半中,您将无法使用自定义模板呈现。在 Expressjs 中拥有自定义错误页面(404)的最佳方法是
app.use(function(req, res, next){
res.status(404).render('404_error_template', {title: "Sorry, page not found"});
});
Place this code at the end of all your URL mappings.
将此代码放在所有 URL 映射的末尾。
回答by Vivek Bajpai
At the last line of app.js just put this function. This will override the default page-not-found error page:
在 app.js 的最后一行,只需要放置这个函数。这将覆盖默认的 page-not-found 错误页面:
app.use(function (req, res) {
res.status(404).render('error');
});
It will override all the requests that don't have a valid handler and render your own error page.
它将覆盖所有没有有效处理程序的请求并呈现您自己的错误页面。
回答by Marius Cotofana
回答by Eric Elliott
express-error-handlerlets you specify custom templates, static pages, or error handlers for your errors. It also does other useful error-handling things that every app should implement, like protect against 4xx error DOS attacks, and graceful shutdown on unrecoverable errors. Here's how you do what you're asking for:
express-error-handler允许您为错误指定自定义模板、静态页面或错误处理程序。它还执行每个应用程序都应该实现的其他有用的错误处理功能,例如防止 4xx 错误 DOS 攻击,以及在不可恢复的错误上正常关闭。以下是你如何做你所要求的:
var errorHandler = require('express-error-handler'),
handler = errorHandler({
static: {
'404': 'path/to/static/404.html'
}
});
// After all your routes...
// Pass a 404 into next(err)
app.use( errorHandler.httpError(404) );
// Handle all unhandled errors:
app.use( handler );
Or for a custom handler:
或者对于自定义处理程序:
handler = errorHandler({
handlers: {
'404': function err404() {
// do some custom thing here...
}
}
});
Or for a custom view:
或者对于自定义视图:
handler = errorHandler({
views: {
'404': '404.jade'
}
});
回答by Dennis Mathew Philip
There are some cases where 404 page cannot be written to be executed as the last route, especially if you have an asynchronous routing function that brings in a /route late to the party. The pattern below might be adopted in those cases.
在某些情况下,404 页面不能被写入作为最后一个路由执行,特别是如果你有一个异步路由功能,它会在晚会上引入一个 /route。在这些情况下可能会采用以下模式。
var express = require("express.io"),
app = express(),
router = express.Router();
router.get("/hello", function (req, res) {
res.send("Hello World");
});
// Router is up here.
app.use(router);
app.use(function(req, res) {
res.send("Crime Scene 404. Do not repeat");
});
router.get("/late", function (req, res) {
res.send("Its OK to come late");
});
app.listen(8080, function (){
console.log("Ready");
});
回答by Lalith
https://github.com/robrighter/node-boilerplate/blob/master/templates/app/server.js
https://github.com/robrighter/node-boilerplate/blob/master/templates/app/server.js
This is what node-boilerplate does.
这就是节点样板所做的。
回答by ASHISH RANJAN
// Add this middleware
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});

