简体   繁体   English

req.login后,护照js req.user不可用

[英]passport js req.user not available after req.login

I am trying to setup my passport sessions correctly. 我正在尝试正确设置我的护照会话。 I have gotten to the point where, after a user signs up - I execute req.login() and then I have a console message, console.log(req.user) . 我已经达到这样的程度,在用户注册后 - 我执行req.login()然后我有一个控制台消息, console.log(req.user) It returns: 它返回:

{ email: 'xxxx', password: 'xxxx', id: 0 }

So it seems as if, right after the user is created, req.user is available. 因此,似乎在创建用户之后, req.user可用。 However, when a user logs in, I have this route: 但是,当用户登录时,我有这条路线:

app.post('/login', passport.authenticate('local-login', { failureRedirect: '/login'}),
      function(req, res) {
         console.log(req.user);
         res.redirect('/users');
      }
);

That console message (from the post call) returns: 该控制台消息(来自post调用)返回:

{ id: null,
  email: 'xxxxx',
  password: 'xxxxx' }

As you can see - upon login - it redirects to /users - this is my get request: 正如您所看到的 - 登录时 - 它重定向到/users - 这是我的获取请求:

app.get('/users', function(req, res){
  console.log(req.user);
  res.render('partials/profile.html');
});

That console message returns undefined - so req.user is not being passed. 该控制台消息返回undefined - 因此没有传递req.user Furthermore, if I examine the session with console.log(req.session) I get: 此外,如果我用console.log(req.session)检查会话,我得到:

{ cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true,
     secure: true },
  passport: {} }

So you can see - there is no passport user in the cookie, it is an empty set. 所以你可以看到 - cookie中没有护照用户,它是一个空集。

Where am I going wrong? 我哪里错了?

Thanks! 谢谢!

I encountered the same problem, and I just set a session name to the user's name in the login post. 我遇到了同样的问题,我只是在登录帖子中将会话名称设置为用户名。 Then I could get it in the rest of the application. 然后我可以在应用程序的其余部分得到它。

app.post('/login', passport.authenticate('local-login', { failureRedirect: '/login'}),
  function(req, res) {
     console.log(req.user);
     req.session.user = req.user;
     res.redirect('/users');
  }
);

So you can access that anywhere. 所以你可以在任何地方访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM