Express Passport (node.js) error handling

前端 未结 3 1781
星月不相逢
星月不相逢 2020-12-07 07:19

I\'ve looked at how error handling should work in node via this question Error handling principles for Node.js + Express.js applications?, but I\'m not sure what passport\'s

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 07:47

    What Christian was saying was you need to add the function

    req.login(user, function(err){
      if(err){
        return next(err);
      }
      return res.send({success:true});
    });
    

    So the whole route would be:

    app.post('/login', function(req, res, next) {
      passport.authenticate('local', function(err, user, info) {
        if (err) {
          return next(err); // will generate a 500 error
        }
        // Generate a JSON response reflecting authentication status
        if (! user) {
          return res.send(401,{ success : false, message : 'authentication failed' });
        }
        req.login(user, function(err){
          if(err){
            return next(err);
          }
          return res.send({ success : true, message : 'authentication succeeded' });        
        });
      })(req, res, next);
    });
    

    source: http://passportjs.org/guide/login/

提交回复
热议问题