在express-validator中发生错误后停止执行流程

时间:2012-01-07 16:27:11

标签: validation node.js express

我正在使用express-validator对Express中的request对象进行表单验证。我做了类似以下的事情:

req.onValidationError(function(msg) {
    res.render('signup', { error: msg });
});

req.check('email', 'Please enter a valid email.').len(1,256).isEmail;
req.check('password', 'Your password must be at least 8 characters.').len(8,256);

var user = {
    email: req.body.email,
    password: req.body.password
};

User.create(user, function(err, result) {
    console.log(err, result);
});

res.render('signup');

问题是执行流程继续,并且在执行User.create()方法时尝试两次渲染相同的资源。由于尝试进行双重渲染,它还会抛出Error: Can't use mutable header APIs after sent.

如何防止这种情况发生?

1 个答案:

答案 0 :(得分:1)

请参阅https://github.com/ctavan/express-validator#readme

var errors = [];
req.onValidationError(function(msg) {
    //res.render('signup', { error: msg });
    errors.push(msg);
});

req.check('email', 'Please enter a valid email.').len(1,256).isEmail;
req.check('password', 'Your password must be at least 8 characters.').len(8,256);

if (errors.length) return res.render('signup', { error: errors.join('\n') });

var user = {
    email: req.body.email,
    password: req.body.password
};

User.create(user, function(err, result) {
    console.log(err, result);
});

res.render('signup');