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


当前回答

覆盖express中的所有HTTP动词

为了覆盖所有HTTP动词和所有剩余路径,您可以使用:

app.all('*', cb)

最终的解决方案是这样的:

app.all('*', (req, res) =>{
    res.status(404).json({
        success: false,
        data: '404'
    })
})

你不应该忘记把路由器放在最后。 因为路由器的顺序很重要。

其他回答

你问题的答案是:

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

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

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

//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?

在某些情况下,404页面不能被写入并作为最后一个路由执行,特别是如果您有一个异步路由功能,从而引入了一个迟到的/路由。在这些情况下可以采用下面的模式。

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");
});

在Express中,404响应不是错误的结果,因此错误处理程序中间件不会捕获它们。你所需要做的就是在堆栈的最底部(所有其他函数的下面)添加一个中间件函数来处理404响应:

app.use(function (req, res, next) {
// YOU CAN CREATE A CUSTOM EJS FILE TO SHOW CUSTOM ERROR MESSAGE
  res.status(404).render("404.ejs")
})

https://github.com/robrighter/node-boilerplate/blob/master/templates/app/server.js

这就是node-boilerplate所做的。