Reputation: 237
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 with out repeating the cookie checking code in all app.get.
Suggestions for fixing this? Thanks in advance
Upvotes: 6
Views: 2489
Reputation: 522
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.
Upvotes: 2
Reputation: 146044
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
});
Upvotes: 8