Nodejs perform a common action for all requests

I am using node js with an expression. Now I need to perform a common action for all ex requests. cookie verification

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, checking cookies is a common action for all requests. So, how can I accomplish this without repeating the cookie verification code in all app.get.

Suggestions for fixing this? thanks in advance

+6
source share
3 answers

Check out the loadUser example from express documents on Route Middleware . Template:

 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 }); 
+8
source

app.all or use middleware.

+3
source

Using middleware is high priority, high performance and very cheap. If the general action that needs to be performed is a tiny function that I propose to add to this very simple intermediate link in the app.js file:

 ... app.use(function(req,res,next){ //common action next(); });... 

If you use a router: write the code before the app.use(app.router); .

+2
source

Source: https://habr.com/ru/post/897125/


All Articles