Node.js:如何在Express中的所有HTTP请求上做些什么?

所以我想做一些事情:

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

当前的app.all()需要一个path,如果我举例来说这个/然后只有当我在主页上,所以它不是全部..

在简单的node.js中,就像在创buildhttp服务器之后,在执行页面路由之前一样简单。

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

Express基于Connect中间件。

Express的路由function由您的应用程序的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); 

就这么简单。

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