I am using node js with express. Now i need to perform an common action for all requests ex. cookie checking
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
});
Here cookie checking is an common action for all request. So how can i perform this w开发者_开发百科ith out repeating the cookie checking code in all app.get.
Suggestions for fixing this? Thanks in advance
Check out the loadUser example from the express docs on Route Middleware. The pattern is:
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
or use a middleware.
Using middleware is high reccomended, high performable and very cheap. If the common action to be performed is a tiny feature I suggest to add this very simple middleware in your app.js file:
...
app.use(function(req,res,next){
//common action
next();
});...
If you use router : write the code before the app.use(app.router);
instruction.
精彩评论