【问题标题】:Node Express: Joi not converting to lowercaseNode Express:Joi 未转换为小写
【发布时间】:2019-09-07 22:58:52
【问题描述】:

在我的路由器中我有

router.post('/user/register', User.validateRegister, User.register);

验证注册函数添加了 .lowercase() 和 trim() 但是当数据进入数据库时​​它不是小写的?

  static validateRegister = async (req: Request, res: Response, next: NextFunction) => {
    const schema = Joi.object().keys({
      email: Joi.string().lowercase().trim().email({ minDomainSegments: 2 }),
      fullName: Joi.string().trim().max(30),
      password: Joi.string().trim().min(5),
    });
    const email = req.body.email;
    const password = req.body.password;
    const fullName = req.body.fullName;
    Joi.validate({ email, password, fullName }, schema, (err) => {
      if (!err) next(); else res.json(err.details);
    });
  };

下面是注册函数

  static register = async (req: Request, res: Response) => {
    const email = req.body.email;
    const password = req.body.password;
    const fullName = req.body.fullName;
    const alreadyRegistered = await userModel.findOne({email}).exec();
    if (!alreadyRegistered) {
      const hashedPassword = await bcrypt.hash(password, 10);
      if (!hashedPassword) {
        res.status(500).send({ message: 'Failed to encrypt your password' });
      } else {
        const user = new userModel({email, password: hashedPassword, fullName} as UserModelInterface);
        const saved = await user.save();
        if (!saved) {
          res.status(500).send({ message: 'Failed to register you' });
        } else {
          res.status(200).send({ message: 'You are now registered' });
        }
      }
    } else {
      res.status(400).send({ message: 'You have already registered' });
    }
  };

我的问题是为什么 Joi 没有将电子邮件转换为小写?

【问题讨论】:

    标签: node.js express joi


    【解决方案1】:

    您正在使用从前端发送的数据req.body,如果您需要经过验证的数据,那么您可以使用类似

    Joi.validate({ email, password, fullName }, schema, (err, val) => {
      if (!err) {
        req.validatedBody = val;
        //req.body = val;
        next();
      } else {
        res.json(err.details);
      }
    }); 
    

    在注册函数中

    const email = req.validatedBody.email;
    const password = req.validatedBody.password;
    const fullName = req.validatedBody.fullName;
    

    即使您可以覆盖req.body(参见注释行),那么您也不需要更改注册功能

    【讨论】:

    • 确实是我追的那条评论,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 2022-01-24
    • 2018-11-21
    • 1970-01-01
    相关资源
    最近更新 更多