【问题标题】:Validating req.params with express validator使用 express 验证器验证 req.params
【发布时间】:2019-09-01 12:38:14
【问题描述】:

我希望用户能够在端点中写入特定的帐号,并尝试验证端点参数是否存在于我的数据库中。我无法让它工作,请问我做错了什么?

我的验证

const validateReq: [
param('accountNumber').exists().custom(acctNo => accountNumberExist(acctNo)),]

My accountNumberExist 函数

    accountNumberExist(inputAcct) {
    const isfound = accounts.find(account => account.accountNumber === inputAcct);
    if (isfound === undefined) throw new Error('Account Number not found');
  }

我的帐户文件

    const accounts = [
  {
    id: 1,
    accountNumber: 1234567890,
    createdOn: new Date(),
    owner: 1,
    type: 'current',
    balance: 23444.43,
    status: 'active',
  },
  {
    id: 2,
    accountNumber: 1234167890,
    createdOn: new Date(),
    owner: 1,
    type: 'savings',
    balance: 2233444.43,
    status: 'active',
  },
  {
    id: 3,
    accountNumber: 9987654321,
    createdOn: new Date(),
    owner: 2,
    type: 'saving',
    balance: 73444.43,
    status: 'active',
  },
];

但这总是抛出“找不到帐号”错误,即使 req.param 存在于我的帐户数据库中。

【问题讨论】:

    标签: javascript api express endpoint express-validator


    【解决方案1】:

    参数被 express 中间件解析为string。假设我对下面定义的路径提出了请求,例如 /some/1000

    app.get('/some/:path', (req, res, next) => {
      console.log(typeof req.param.path)
      // outputs string
    })
    

    因此您需要将传入参数解析为整数(数字),因为您已将 accountNumber 存储为整数。因此,将toInt 添加到如下链应该可以解决它:

    const validateReq: [
      param('accountNumber').exists().toInt().custom(acctNo => accountNumberExist(acctNo)),
    ]
    

    【讨论】:

    • 作为 express-validator 维护者:这将是解决这个问题的首选方式;)
    • 如果我在参数和正文中有值怎么办?例如:重置密码 -> 我们在参数上传递重置密码令牌并在正文中传递电子邮件。我们该如何处理这种情况?
    • 那么这里使用这个 sh*** validateReq 变量吗?
    【解决方案2】:

    accountNumber 里面的 accounts 数组是一个数字,而 req.params.accountNumber 是一个字符串。您需要转换数据类型。你可以这样做

        accountNumberExist(inputAcct) {
            const isfound = accounts.find(account => account.accountNumber.toString() === inputAcct);
            if (isfound === undefined) throw new Error('Account Number not found');
      }
    

    【讨论】:

      【解决方案3】:

      我认为问题在于您的查询。 find 方法以异步方式运行,这就是为什么 isfound 属性不包含您期望的数据。这是一个使用promises 的简单方法,对我来说效果很好。

      // Here is your function.
      accountNumberExist(inputAcct) {
          return accounts.find({accountNumber: inputAcct})
          .then(result => {
              if (result.length == 0) {
                  console.log("Account Number not found");
                  return Promise.reject('Account Number not found');
              }
              return Promise.resolve();
          });
      
      }
      

      【讨论】:

      • OP 使用的是普通数组。不涉及异步内容。
      • @gustavohenke 这段代码的问题在哪里?官方文档也推荐express-validator.github.io/docs/…
      • 如上所述,OP使用的是普通数组,上面提到的.find()Array.prototype.find——不是某种DB查询或API调用。
      猜你喜欢
      • 2020-11-07
      • 2016-11-17
      • 2020-02-20
      • 1970-01-01
      • 1970-01-01
      • 2019-12-05
      • 2012-09-14
      • 1970-01-01
      • 2022-08-13
      相关资源
      最近更新 更多