Node.js Express:在app.get()和app.post()之前执行每个HTTP请求的钩子?

我不想在每个app.get()的顶部放置一个身份validation函数,我怎么才能在app.get()之前的每个请求上执行代码?

在路由之前build立一个中间件:

 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 

你也可以这样做:

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