开发者

nodejs perform common action for all request

开发者 https://www.devze.com 2023-04-04 09:11 出处:网络
I am using node js with express. Now i need to perform an common action for all requests ex. cookie checking

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消