简体   繁体   中英

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) . It returns:

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

So it seems as if, right after the user is created, req.user is available. 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:

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

As you can see - upon login - it redirects to /users - this is my get request:

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. Furthermore, if I examine the session with console.log(req.session) I get:

{ 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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