所以,这以前有效,突然决定停止工作,我不知道为什么。
编辑:更新了代码以显示我目前得到的内容
router.post('/register', async (req, res) => {
// let query
let query;
// Start email checks
req.check('email', 'Email is not valid.')
.isEmail()
.custom(async value => {
query = {email: value};
User.findOne(query).then(user => {
if (user) return false;
});
}).withMessage('Email is in use.');
// Start username checks
req.check('username', 'Username is required.')
.notEmpty()
.isLength({ min: 5, max: 15}).withMessage('Username requires 5-15 alphanumberic characters.')
.isAlphanumeric().withMessage('Username must be alphanumeric only.')
.custom(async value => {
query = {username: value}
User.findOne(query).then(user => {
if (user) return false;
});
}).withMessage('Username is in use.');
// Start password checks
req.check('password', 'Password is required.')
.notEmpty()
.isLength({min: 5}).withMessage('Password must be atleast 5 characters long.');
req.check('confirmPassword', 'Confirm Password is required.')
.notEmpty()
.custom(value => value === req.body.password).withMessage('Password must match');
const errors = await req.getValidationResult();
//console.log(errors);
if (!errors.isEmpty()) {
res.render('index', {
errors: errors.mapped()
});
} else {
let newUser = new User({
email: req.body.email,
username: req.body.username,
password: req.body.password,
});
let hash = bcrypt.hashSync(req.body.password, 10);
newUser.password = hash;
newUser.save(err => {
if (err) {
console.log(err);
} else {
res.render('index', {
success: 'Registration Successful'
});
}
});
}
});
所以很明显它与我的自定义检查有关,我不知道为什么。
编辑: 似乎有困惑。检查工作正常,我遇到的问题是它在我想要的时候填充错误。如果我尝试使用同一电子邮件注册,它将拉出用户并检查我的 if 语句。如果我使用 Promise.reject() 它不起作用。如果我使用 false,则不起作用。同样,检查本身有效,错误处理似乎无效。
编辑二: 所以我尝试了这个方法(所有其他代码仍然相同)
// Start email checks
req.checkBody('email', 'Email is not valid.')
.isEmail()
.custom(value => {
query = {email: value}
User.findOne(query).then(user => {
if (user) console.log('Email Exists'); return false;
});
}).withMessage('Email in use.');
// Start username checks
req.check('username', 'Username is required.')
.notEmpty()
.isLength({ min: 5, max: 15}).withMessage('Username requires 5-15 alphanumberic characters.')
.isAlphanumeric().withMessage('Username must be alphanumeric only.')
.custom(value => {
query = {username: value}
User.findOne(query).then(user => {
if (user) console.log('Username Exists'); return false;
});
}).withMessage('Username in use.');
最佳答案
这应该有效。由于 Node.js 是非渲染阻塞的,因此数据库查询在继续下一步之前可能无法完成。您可以使用我在下面发布的格式或尝试异步库,在这种情况下,应将 await
关键字放置在 User.findOne
User.findOne(query).then(user=>{
if(user) return false
}).catch(err => console.log(err))
关于node.js - 快速验证未产生正确的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53774902/