nodejs为所有请求执行通用操作

我用express来使用节点js。 现在我需要为所有请求执行一个共同的行动。 cookie检查

app.get('/',function(req, res){ //cookie checking //other functionality for this request }); app.get('/show',function(req, res){ //cookie checking //other functionality for this request }); 

这里cookie检查是所有请求的通用操作。 那么我怎样才能在所有app.get中重复cookie检查代码呢。

解决这个问题的build议? 提前致谢

查看路由中间件上的express文档中的loadUser示例 。 模式是:

 function cookieChecking(req, res, next) { //cookie checking next(); } app.get('/*', cookieChecking); app.get('/',function(req, res){ //other functionality for this request }); app.get('/show',function(req, res){ //other functionality for this request }); 

app.all或使用中间件。

使用中间件是很好的build议,高性能和非常便宜。 如果要执行的常见操作是一个小function,我build议在app.js文件中添加这个非常简单的中间件:

 ... app.use(function(req,res,next){ //common action next(); });... 

如果你使用路由器 :在app.use(app.router);之前写代码app.use(app.router); 指令。