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
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.
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.
listen() method creates a listener on the specified port or path.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With