nodejs对所有请求执行公共操作

时间:2011-09-12 06:14:28

标签: node.js express

我正在使用带有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检查代码的情况下执行此操作。

修复此问题的建议?提前致谢

3 个答案:

答案 0 :(得分:8)

查看loadUser example from the express docs on Route Middleware。模式是:

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

答案 1 :(得分:3)

app.all或使用中间件。

答案 2 :(得分:2)

使用中间件具有很高的推荐性,高性能且非常便宜。如果要执行的常见操作是一个很小的功能,我建议在 app.js 文件中添加这个非常简单的中间件:

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

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

相关问题