【问题标题】:creating authentication function node.js创建身份验证功能 node.js
【发布时间】:2021-04-28 09:09:27
【问题描述】:

我有一种很好的方式来检查某人是否使用 express-session 进行了身份验证。方法如下:

if (req.session.loggedin) {

... do code ...

} else {
    req.session.destory;
    res.redirect('/login')
}

但是,我可能想创建某种中间件,或者调用该函数的所有其他函数。像这样。

function auth (req, res) {
   if (req.session.loggedin) {

        return;

   } else {
    req.session.destory;
    res.redirect('/login')
   }

}

app.get('/home', (req, res) => {
  auth()
... do code ...

}) 

或:

app.get('/home', (req, res, auth) => {
... do code ...
})

这可能吗,如果可以,我该怎么做?

【问题讨论】:

    标签: node.js express express-session


    【解决方案1】:

    使用验证会话制作auth 中间件,记住调用next 函数时,任何一个都很好。

    function auth(req, res, next) {
       if (req.session.loggedin) {
           return next(); // call next function to go to next handler
       } else {
          req.session.destory;
          res.redirect('/login')
       }
    }
    

    然后,为每个需要身份验证的路由器应用中间件:

    app.get('/home', auth, (req, res) => { // apply auth before "do code"
       // ... do code ...
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-06
      • 2018-07-22
      • 1970-01-01
      • 2019-07-23
      • 2012-10-19
      • 2018-07-19
      • 2018-12-27
      • 1970-01-01
      相关资源
      最近更新 更多