Node.js执行所有请求的常见操作

6

我正在使用Node.js和Express。现在我需要对所有请求执行一项常见操作,例如检查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个回答

8

请查看从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 
}); 

3

app.all or use a middleware.


2

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接