护照登记成功回调

时间:2016-06-28 22:36:50

标签: javascript node.js express passport.js

router.post('/register', function(req, res, next){
    var name            = req.body.name;
    var email           = req.body.email;
    var username        = req.body.username;
    var password        = req.body.password;
    var password2       = req.body.password2;

    req.checkBody('name', 'Name field is required').notEmpty();
    req.checkBody('email', 'Email field is required').notEmpty();
    req.checkBody('email', 'Email must be a valid email address').isEmail();
    req.checkBody('username', 'Username field is required').notEmpty();
    req.checkBody('password', 'Password field is required').notEmpty();
    req.checkBody('password2', 'Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();

    if(errors){
        res.render('register');

    } else {

        passport.authenticate('local-register',{
            successRedirect: '/dashboard',
            failureRedirect: '/register'
        })(req, res, next)
    }
});

我希望在用户注册后再做一些操作,比如在db中输入相关数据。但我不知道护照成功回调在哪里

1 个答案:

答案 0 :(得分:0)

查看passport documentation,您应该可以通过自行重定向来实现此目的。

示例:

app.post('/login',
  passport.authenticate('local'),
  function(req, res) {
    // If this function gets called, authentication was successful.
    // `req.user` contains the authenticated user.
    res.redirect('/users/' + req.user.username);
  });

因此,您的代码可能会被修改为类似的内容......

router.post('/register', function(req, res, next){
    var name            = req.body.name;
    var email           = req.body.email;
    var username        = req.body.username;
    var password        = req.body.password;
    var password2       = req.body.password2;

    req.checkBody('name', 'Name field is required').notEmpty();
    req.checkBody('email', 'Email field is required').notEmpty();
    req.checkBody('email', 'Email must be a valid email address').isEmail();
    req.checkBody('username', 'Username field is required').notEmpty();
    req.checkBody('password', 'Password field is required').notEmpty();
    req.checkBody('password2', 'Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();

    if(errors){
        res.render('register');
    } else {
        passport.authenticate('local-register',{ })(req, res, function(returnCode) {
            // Yay successfully registered user
            // Do more stuff
            console.log(returnCode);     // Check what this value is and redirect accordingly.
            res.redirect('/dashboard/'); // How redirect can potentially be done
       })
    }
});

我不确定returnCode值是什么,因为这取决于local-register策略的实施。

无论如何,returnCode可能会用于检查注册是否成功,并根据其值 - 相应地重定向用户。