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

后端 未结 2 1230
Happy的楠姐
Happy的楠姐 2021-02-01 05:17

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()?

相关标签:
2条回答
  • 2021-02-01 05:31

    You can also do:

    app.all('*', auth.requireUser);
    
    0 讨论(0)
  • 2021-02-01 05:46

    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
    
    0 讨论(0)
提交回复
热议问题