我在express中使用node js。现在,我需要对所有请求ex执行一个公共操作。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检查代码的情况下执行此操作呢?
解决这个问题的建议是什么?提前感谢
发布于 2011-09-12 22:08:02
查看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
}); 发布于 2011-09-12 15:17:07
app.all或使用中间件。
发布于 2014-01-13 22:08:33
使用中间件具有高可推荐性、高可执行性和低成本等优点。如果要执行的常见操作是一个很小的功能,我建议在您的app.js文件中添加这个非常简单的中间件:
...
app.use(function(req,res,next){
//common action
next();
});...如果您使用router :在app.use(app.router);指令之前编写代码。
https://stackoverflow.com/questions/7383943
复制相似问题