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


当前回答

首先,创建一个route js文件。接下来,创建一个错误。Ejs文件(如果您正在使用Ejs)。最后,在路由文件中添加以下代码

router.get('*', function(req, res){
    res.render('error');
});

其他回答

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

app.use(function (req, res) {
    res.status(404).render('error');
});

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

发送到自定义页面:

app.get('*', function(req, res){
  if (req.accepts('html')) {
     res.send('404', '<script>location.href = "/the-404-page.html";</script>');
     return;
  }
});

我认为你应该首先定义你所有的路线,然后作为最后的路线添加

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

一个示例应用程序的工作:

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');

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?
app.get('*',function(req,res){
 res.redirect('/login');
});

你问题的答案是:

app.use(function(req, res) {
    res.status(404).end('error');
});

有一篇很棒的文章讲述了为什么这是最好的方法。