Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

node.js - Difference between the 2 passport.authenticate methods

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.


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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...