2014-11-21 46 views
3

我寫了一個註冊表格表,我使用passport-local是工作,但我想要添加express-validator來驗證我的表單數據。我想補充的路由器上的驗證,這是我的router/index.js代碼:帶有護照的NodeJS快速驗證器

/* Handle Registration POST */ 
router.post('/signup', function(req, res) { 
    req.assert('email', 'A valid email is required').isEmail(); 
    var errors = req.validationErrors(); 

    if(errors){ //No errors were found. Passed Validation! 
     res.render('register', { 
     message: 'Mail type fault', 
     errors: errors 
     }); 
    } 
    else 
    { 
    passport.authenticate('signup', { 
     successRedirect: '/home', 
     failureRedirect: '/signup', 
     failureFlash : true 
    }); 
    } 
}); 

的驗證工作,但如果成功,那麼該網頁將在加載很長一段時間也沒有迴應。我有搜索護照文件,但沒有想法解決它。

這是原產地的代碼,它的工作

/* Handle Registration POST */ 
router.post('/signup', passport.authenticate('signup', { 
    successRedirect: '/home', 
    failureRedirect: '/signup', 
    failureFlash : true 
})); 

我想我可以使用jQuery退房,但我不這樣做。因爲我只是想嘗試使用驗證器和護照。

回答

0

做在LocalStrategy而不是路由器的驗證應該只是罰款:在LocalStartegy

passport.use('signup', new LocalStrategy({ 
    passReqToCallback: true 
}, function(req, username, password, callback) { 
    /* do your stuff here */ 
    /* req.assert(...) */ 
})); 
7

把驗證代碼應該工作,但是,我個人會先做認證,一旦它已通過使用護照。

考慮下面的內容:

router.post('/login',function(req,res){ 

    req.checkBody('username', 'Username is required').notEmpty(); 
    req.checkBody('password', 'Password is required').notEmpty(); 

    //validate 
    var errors = req.validationErrors(); 

    if (errors) { 

     res.render('signup',{user:null,frm_messages:errors}); 

    } 
    else{ 
     passport.authenticate('login',{ 
      successRedirect:'/', 
      failureRedirect: '/login', 
      failureFlash : true 
     })(req,res); // <---- ADDD THIS 
    } 
}); 
+0

我這樣做,但它給了我錯誤:類型錯誤:req.checkBody不是一個函數 – 2017-05-12 14:01:03

3
/* Handle Registration POST */ 
router.post('/signup', checkEmail, 
    passport.authenticate('signup', { 
     successRedirect: '/home', 
     failureRedirect: '/signup', 
     failureFlash : true 
    }); 
}); 

function checkEmail(req, res, next){ 
    req.checkBody('username', 'Username is required').notEmpty(); 
    req.checkBody('password', 'Password is required').notEmpty(); 
    //validate 
    var errors = req.validationErrors(); 
    if (errors) { 
     res.render('signup',{user:null,frm_messages:errors}); 
    } else { 
     next(); 
    } 
}