我写了一个注册表单,我使用passport-local
工作,但我想添加express-validator
来验证我的表单数据。我在路由器上添加验证,这是我的router/index.js
代码:
/* 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 :(得分:9)
在LocalStartegy中放置验证码应该可行但是,我个人首先要进行身份验证,一旦通过使用护照。
考虑以下事项:
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
}
});
答案 1 :(得分:4)
/* 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();
}
}
答案 2 :(得分:0)
在LocalStrategy而不是路由器中进行验证应该可以正常工作:
passport.use('signup', new LocalStrategy({
passReqToCallback: true
}, function(req, username, password, callback) {
/* do your stuff here */
/* req.assert(...) */
}));
答案 3 :(得分:0)
我完全有同样的问题。我只是使用了一个中间件来检查验证,如果验证成功,我会在其中调用next()。
router.post("/login",
[check('email').isEmail().withMessage("A valid email is required")],
(req, res, next) => {
// Check validation.
const errors = validationResult(req);
if (!errors.isEmpty()) {
// handle your error (redirect, render, ..).
}
// if validation is successful, call next() to go on with passport authentication.
next();
},
passport.authenticate("login", {
successRedirect: "/",
failureRedirect: "/login",
failureFlash: true
})
);