jQuery AJAX call to Passportjs login on Express (nodejs) Framework

前端 未结 1 995
故里飘歌
故里飘歌 2021-01-18 09:45

I\'m trying to use AJAX to call a login verification using Passport library on a Express application. Im using local strategy like this:

router.post(\'/login         


        
相关标签:
1条回答
  • 2021-01-18 10:23

    This should work, untested, let me know if there's typos.

    Basically, you need your express app to listen for a POST request on /login, in this route, you can add your passport auth.

    app.post('/login', function(req, res, next) {
        passport.authenticate('loginUsers', function(err, user, info) {
            if (err) { return next(err); }
            if (!user) { return res.render('account'); }
            req.logIn(user, function(err) {
                if (err) { return next(err); }
                return res.json({detail: info});
            });
        })(req, res, next);
    });
    

    Also, in your strategy, make sure the fields name are correct ie:

    passport.use('loginUsers',new LocalStrategy({
                usernameField : 'username',
                passwordField : 'password',
                passReqToCallback : true
            },
    
    0 讨论(0)
提交回复
热议问题