Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

It is the same login route. Just 2 different approaches.

First route

router.post('/login', passport.authenticate('local',{session:false}),async (req,res) => { 
  console.log("


 ------------------------222222")
        console.log(req.user);
    });

and the request object has the user & is displayed.

Whereas in the second route

router.post('/login', (req, res, next) => {
  passport.authenticate('local', async (err, user, info) =>{
    if(err){
      console.log(err);
    }
    console.log("


 ------------------------")
        console.log(req.user); //undefined
    if(user){
      // it works here 
    }
    else{
      res.status(422).json(info);
    }
  })(req, res, next);
});

console.log(req.user); shows undefined. but the user has the user details fetched from the mongo db.

Can someone explain me please.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
221 views
Welcome To Ask or Share your Answers For Others

1 Answer

In the second function, you get the user in the user key. However, you ll have to add it to req object. It can be done like this

if(user){
  // it works here 
  req.user = user;
}

In the first case, it is already added to the req object since it has already executed passport.authenticate before getting into the next async function.
If you print the req.user after the if else, it will give you the exact details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...