我正在使用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.
。如何防止这种情况发生?
最佳答案
见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');
关于validation - express-validator中的错误后停止执行流程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8771148/