【问题标题】:req.user and Is Authenticated always falsereq.user 和 Is Authenticated 总是假的
【发布时间】:2018-07-09 19:34:59
【问题描述】:

我正在使用 express.js 反应(在 router/user.js 内)

router.get("/", function (req, res) {
  console.log("this is u" , req.user)
   console.log(req.isAuthenticated());
  if (req.user) {
     res.json({ user: req.user })
  } else {
    res.json({ user: 'does not exsist' })
}
});

在这里,console.log 显示对它们的值始终未定义

console.log("this is u" , req.user)
       console.log(req.isAuthenticated());

上面的代码总是console.log false,现在我浏览了其他例子,他们提到问题可能是由于你把东西放在server.js(或app.js)中的方式,因此我检查并认为我的问题不是因为这个原因,反正这就是我添加东西的方式

app.use(session({
  secret: 'keyboard cat', // -> used to encode and decode the session, the seceret we used will be used to encode to decode
  resave: true,
  saveUninitialized: true,
}));
app.use(passport.initialize());
app.use(passport.session());

//Session



passport.use(new LocalStrategy(user.authenticate()));
passport.serializeUser(user.serializeUser());
passport.deserializeUser(user.deserializeUser());

如果有人想查看,这是我完整的正确存储库:https://github.com/irohitb/litifier-

现在,谁能指导我解决这个问题?

【问题讨论】:

    标签: javascript node.js reactjs express passport.js


    【解决方案1】:

    这是因为登录过程没有被执行。 这会导致 cookie 未发送,从而导致在下一个请求中未读取 cookie,从而导致req.isAuthenticated() 返回false

    来自passport.js docs,

    请注意,当使用自定义回调时,它会成为应用程序的 建立会话的责任(通过调用 req.login())和 发送响应。

    解决方法:

    因为这看起来像你的注册页面,我认为你不需要在这里做passport.authenticate。那是为了登录。删除它。

    注册新用户后,请执行以下操作:

    req.logIn(user, function (err) {
         if (err) {
             return next(err);
         }
         return res.json(user) // send whatever you want or redirect
    });
    

    【讨论】:

    • 嘿@Dushyant,你指的是这里的post request吗?
    • 是的,在"/" 发帖。此外,该声明看起来无效github.com/irohitb/litifier-/blob/master/server/routes/…
    • 试过了,说req#login需要回调函数
    • 是的,给req.login(user) ofcourse 提供回调
    • 修复了它。不过很好奇,您是如何发现此声明无效的? assport.authenticate("local"),function(req, res){是在平台注册的时候认证用户?
    【解决方案2】:

    尝试在路由中添加 {credentials: 'include'}

    例子

    get('/test', {credentials: 'include'})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-28
      • 2019-10-11
      • 2020-10-13
      • 1970-01-01
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多