Node.js Express: Execute hook on every HTTP request, before app.get() and app.post()?

I don't want to put an authentication function at the top of every app.get(), how can I execute code on every request, before app.get()?

Answers


Set up a middleware before your routes:

function myMiddleware (req, res, next) {
   if (req.method === 'GET') { 
     // Do some code
   }

   // keep executing the router middleware
   next()
}

app.use(myMiddleware)

// ... Then you load the routes

You can also do:

app.all('*', auth.requireUser);

Need Your Help

Difference between LEFT JOIN and LEFT JOIN FETCH in Hibernate?

hibernate hql fetching-strategy

I am trying to understand the difference between LEFT JOIN and LEFT JOIN FETCH in Hibernate.

Calculating area enclosed by arbitrary polygon on Earth's surface

math geometry gis geography

Say I have an arbitrary set of latitude and longitude pairs representing points on some simple, closed curve. In Cartesian space I could easily calculate the area enclosed by such a curve using Gr...