【问题标题】:Express Validator, one function that will check multiple formsExpress Validator,一种检查多种表格的功能
【发布时间】:2020-08-25 23:31:36
【问题描述】:

我一直在尝试使用 Express Validator,但是遇到了一个问题。

目前,我正在使用一个带有变量的路由(即操作,例如更新名称、电子邮件、密码等)将更新的用户数据发送到服务器。

我正在使用一个查看操作的 switch 语句,并对用户数据进行相关更新。

我想要一个验证函数,它也有一个 switch 语句,它将确定它需要验证什么。

目前我有这个...

这个验证规则:

const validationRules = () => {
  console.log("validating...");

  return [
    // names must be 1 or more
    body("firstName").isLength({ min: 1 }),
    body("lastName").isLength({ min: 1 }),
  ];
};

发帖请求:

app.post(
  "/api/user/update/:action",
  validationRules(),
  validate,
  (req, res) => {
    const { id } = req.body;
    const { action } = req.params;

    const updateDatabase = (id, updateObject) => {
      UserModel.findOneAndUpdate(
        { _id: id },
        { $set: updateObject },
        {
          useFindAndModify: false,
        }
      )
        .then((user) => {
          console.log(user);
          res.sendStatus(200);
        })
        .catch((err) => {
          console.log(err);
          res.status(403).send({ error: err });
        });
    };

    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(422).json({ errors: errors.array() });
    } else {
      let update = {};

      switch (action) {
        case "name":
          const { firstName, lastName } = req.body;
          update = {
            "userInfo.firstName": firstName,
            "userInfo.lastName": lastName,
          };
          break;

        case "email":
          const { email } = req.body;
          console.log(email);
          update = {
            "userInfo.email": email,
          };
          break;

        case "mobile":
          const { mobile } = req.body;
          update = {
            "userInfo.mobile": mobile,
          };
          break;
        default:
          console.log("nothing matched so nothing updated");
          break;
      }
      updateDatabase(id, update);
    }
  }
);

【问题讨论】:

    标签: node.js express validation express-validator


    【解决方案1】:

    您可以在那里制作一个简单的中间件和开关盒:

    这是一个例子:

    const app = require('express')();
    
    const validatorMiddleware = (req, res, next)=>{
      switch(req.params.action){
        case 'foo':
          //here you will `return` the rules
          console.log('foo');
          break;
        case 'bar':
          //here you will `return` the rules
          console.log('bar');
          break;
        default: console.log("default");
      }
      next();
    }
    app.get('/:action', validatorMiddleware, (req, res)=>{
      res.send(req.params);
    })
    
    app.listen(8080, ()=>{
      console.log('started');
    })
    

    对于您的情况,它将是这样的:

    const validationRules = (req, res, next) => {
      console.log("validating...");
      switch (req.params.action) {
        case "name":
          return [
            // names must be 1 or more
            body("firstName").isLength({ min: 1 }),
            body("lastName").isLength({ min: 1 }),
          ];
      }
      next();
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多