Node.js:如何对Express中的所有HTTP请求执行某些操作?

Ada*_*dam 30 http request connect node.js express

所以我想做一些事情:

app.On_All_Incomeing_Request(function(req, res){
    console.log('request received from a client.');
});
Run Code Online (Sandbox Code Playgroud)

当前app.all()需要一个路径,如果我举例说明,/那么只有当我在主页上时它才有效,所以它并不是全部......

在plain node.js中,它就像在创建http服务器之后,在我们进行页面路由之前编写任何内容一样简单.

那么如何用express来做到这一点,最好的方法是什么呢?

Rah*_*ane 47

Express基于Connect中间件.

Express的路由功能由router您的应用程序提供,您可以自由地将自己的中间件添加到您的应用程序中.

var app = express.createServer();

// Your own super cool function
var logger = function(req, res, next) {
    console.log("GOT REQUEST !");
    next(); // Passing the request to the next handler in the stack.
}

app.configure(function(){
    app.use(logger); // Here you add your logger to the stack.
    app.use(app.router); // The Express routes handler.
});

app.get('/', function(req, res){
    res.send('Hello World');
});

app.listen(3000);
Run Code Online (Sandbox Code Playgroud)

就这么简单.

(PS:如果你只想要一些日志记录,你可以考虑使用Connect提供的记录器)

  • 或者`app.all("*",cb)`也可以 (28认同)
  • @Raynos我觉得你应该用`app.all("*",cb)`解决方案添加答案,包括讨论为什么/为什么不使用它(我假设大多是文体).知道选项是相关的. (6认同)
  • `app.configure` 不是一个函数? (3认同)

Aba*_*dis 12

你应该做这个:

app.all("*", (req, res, next) => {
    console.log(req); // do anything you want here
    next();
});
Run Code Online (Sandbox Code Playgroud)