如何将404错误重定向到ExpressJS中的页面?

192 node.js express

我不知道这样做的功能,有人知道吗?

Fel*_*lix 261

我发现这个例子非常有帮助:

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.send({ error: 'Not found' });
    return;
  }

  // default to plain-text. send()
  res.type('txt').send('Not found');
});
Run Code Online (Sandbox Code Playgroud)

  • 现在这个问题出现在常见问题解答http://expressjs.com/starter/faq.html#how-do-you-handle-404s- (9认同)
  • 对于 JSON 响应,最好使用 `res.json` 而不是 `res.send()`。它们在您的代码中的行为相同,但使用 `res.json` 会在将对象自动转换为字符串方面发挥一些作用,而 `.send()` 不会。安全总比后悔好。http://expressjs.com/api.html#res.json (4认同)
  • 应该使用`res.format`而不是`req.accepts` (3认同)
  • 我认为在那之前没有找到匹配的路线。 (2认同)
  • 仅供参考,现在不推荐使用`app.router`.请参阅https://github.com/strongloop/express/wiki/Migrating-from-3.x-to-4.x#approuter (2认同)

Alf*_*red 143

我认为您应首先定义所有路线,并作为最后一条路线添加

//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
  res.status(404).send('what???');
});
Run Code Online (Sandbox Code Playgroud)

一个有效的示例应用程序:

app.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');
Run Code Online (Sandbox Code Playgroud)
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?
Run Code Online (Sandbox Code Playgroud)

  • 这不适合我,但后来发现我的`app.use(express.static(...))`来自`app.use(app.router)`.一旦我切换它们一切都很好. (25认同)
  • 嗯......问题是"*"已经匹配了.js和.css文件,并且它们没有在应用程序中指定......好吧,我不知道是否有某种方法可以准确地捕获同样的事情是404错误,或者是一种覆盖"无法获取..."消息的方法.无论如何,谢谢你 (6认同)
  • +1为您的答案添加@ Stephen的评论.这对我来说不起作用,直到我在app.use(express.static(...)之后放app.use(app.router) (5认同)
  • `app.get('/ public/*',function(req,res){res.sendfile(__ dirname +'/ public /'+ req.url);})`您可以使用此路由发送静态文件.它可以在上面的"*"路线上正常工作.`app.use(express.static(__ dirname +'/ public'));`对我不起作用,有线. (4认同)
  • 您是否使用静态中间件,因为这样您仍然可以提供静态文件? (2认同)

Gan*_*mar 33

您可以将中间件放在抛出NotFound错误的最后位置,
甚至可以直接呈现404页面:

app.use(function(req,res){
    res.status(404).render('404.jade');
});
Run Code Online (Sandbox Code Playgroud)

  • 下次请考虑一些更详细的答案......例子通常很好 - 这是一个很好的例子 - 但是一些解释也可以非常非常好...... (9认同)
  • +1**非常好!**我认为这比最后一个路线更好,因为这样你最后一次不必"使用"你的`app.router`.(如我的情况) (2认同)

Sus*_*pta 31

上面的答案是好的,但是其中一半你不会得到404作为你的HTTP状态代码返回,而在另一半,你将无法有自定义模板渲染.在Expressjs中拥有自定义错误页面(404)的最佳方法是

app.use(function(req, res, next){
    res.status(404).render('404_error_template', {title: "Sorry, page not found"});
});
Run Code Online (Sandbox Code Playgroud)

将此代码放在所有URL映射的末尾.


Viv*_*pai 11

在 app.js 的最后一行,只需要放置这个函数。这将覆盖默认的 page-not-found 错误页面:

app.use(function (req, res) {
    res.status(404).render('error');
});
Run Code Online (Sandbox Code Playgroud)

它将覆盖所有没有有效处理程序的请求并呈现您自己的错误页面。

  • 是您的“app.js 的最后一行”评论有所帮助!谢谢! (4认同)

Mar*_*ana 5

你的问题的答案是:

app.use(function(req, res) {
    res.status(404).end('error');
});
Run Code Online (Sandbox Code Playgroud)

而且,关于为什么它是最好的方式一个伟大的文章在这里