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

问题描述:

所以我想做一些例子:

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

当前 app.all()需要一个路径,如果我给出例如这个 / ,那么它只在我在主页上工作,所以它不是真的全部..

the current app.all() requires a path, and if I give for example this / then it only works when I'm on the homepage, so it's not really all..

在简单的node.js中,在创建http服务器之后,以及在进行页面路由之前,可以简单地编写任何内容。

In plain node.js it is as simple as writing anything after we create the http server, and before we do the page routing.

那么如何用快递来做这个,什么是最好的方法呢?

So how to do this with express, and what is the best way to do it?

Express基于 Connect 中间件。

Express is based on the Connect middleware.

Express的路由功能由路由器提供您的应用程序,您可以自由添加自己的应用程序。

The routing capabilities of Express are provided by the router of your app and you are free to add your own middlewares to your application.

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

这很简单。

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

(PS : If you just want some logging you might consider using the logger provided by Connect)