Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs perform common action for all request

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

like image 540
Kumar Avatar asked Sep 12 '11 06:09

Kumar


People also ask

How does NodeJS handle multiple request?

How NodeJS handle multiple client requests? NodeJS receives multiple client requests and places them into EventQueue. NodeJS is built with the concept of event-driven architecture. NodeJS has its own EventLoop which is an infinite loop that receives requests and processes them.

How many concurrent requests can NodeJS handle?

As is, node. js can process upwards of 1000 requests per second and speed limited only to the speed of your network card. Note that it's 1000 requests per second not clients connected simultaneously. It can handle the 10000 simultaneous clients without issue.

What does the listen () function do in Node js?

listen() method creates a listener on the specified port or path.


3 Answers

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 
}); 
like image 100
Peter Lyons Avatar answered Oct 27 '22 23:10

Peter Lyons


app.all or use a middleware.

like image 22
balupton Avatar answered Oct 27 '22 22:10

balupton


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.

like image 38
Francesco Avatar answered Oct 27 '22 23:10

Francesco