快速验证未产生正确的错误

时间:2018-12-14 07:03:15

标签: node.js express-validator

所以,这在以前是可行的,突然间决定停止工作,我也不知道为什么。

编辑:更新了代码以显示我现在得到的信息

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.');

2 个答案:

答案 0 :(得分:0)

这应该有效。由于node.js是非渲染阻止的,因此数据库查询可能无法继续进行下一步。您可以使用我在下面发布的格式,也可以尝试使用异步库,在这种情况下,应将await关键字放在User.findOne

之前
 User.findOne(query).then(user=>{
     if(user) return false
    }).catch(err => console.log(err))

答案 1 :(得分:0)

最后找到一个答案,这也使它也更容易阅读。我最终制作了自己的自定义验证器:

  customValidators: {
    emailExists: (email) => {
      let query = {email: email};
      return new Promise((resolve, reject) => {
        User.findOne(query, (err, results) => {
          if (results === null) {
            resolve(err);
          }
          reject(results);
        });
      });
    },
    userNameExists: (username) => {
      let query = {username: username};
      return new Promise((resolve, reject) => {
        User.findOne(query, (err, results) => {
          if (results === null) {
            resolve(err);
          }
          reject(results);
        });
      });
    }
  },

然后:

  req.check('email', 'This email is in use.').emailExists();
  req.check('username', 'Username is in use.').userNameExists();
  req.asyncValidationErrors().then(() => {
    console.log('No errors');
    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'
        });
      }
    });
  }).catch(errors => {
    res.render('index', {
      errors: errors
    });
  });