首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在ExpressJS中将404错误重定向到页面?

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

Stack Overflow用户
提问于 2011-06-30 08:46:43
回答 22查看 302.2K关注 0票数 240

我不知道做这件事的函数,有人知道吗?

EN

回答 22

Stack Overflow用户

回答已采纳

发布于 2012-03-21 17:45:38

我发现这个例子很有帮助:

https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js

所以,它实际上是这一部分:

代码语言:javascript
复制
// "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');
});
票数 314
EN

Stack Overflow用户

发布于 2011-07-04 00:48:33

您可以将中间件放在抛出NotFound错误的最后位置,

或者甚至直接呈现404页面:

代码语言:javascript
复制
app.use(function(req,res){
    res.status(404).render('404.jade');
});
票数 46
EN

Stack Overflow用户

发布于 2013-05-15 14:22:38

以上答案都很好,但其中一半不会返回404作为HTTP状态码,而另一半则不能进行自定义模板呈现。在Expressjs中创建自定义错误页面(404)的最好方法是

代码语言:javascript
复制
app.use(function(req, res, next){
    res.status(404).render('404_error_template', {title: "Sorry, page not found"});
});

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

票数 34
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6528876

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档