简体   繁体   English

使用Express Validator验证req.params

[英]Validating req.params with express validator

I want the user to be able to write a specific account number in the endpoint, been trying to validate the endpoint param if it exists in my database. 我希望用户能够在端点中写一个特定的帐号,并试图验证端点参数(如果它存在于我的数据库中)。 I couldn't get it to work, please what am I doing wrong? 我无法正常工作,请问我做错了什么?

My validation 我的验证

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

My accountNumberExist function 我的accountNumberExist函数

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

My accounts file 我的帐户档案

    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',
  },
];

But this is always throwing the 'Account Number not found' error even though, the req.param exists in my accounts database. 但是,即使req.param存在于我的帐户数据库中,也始终会引发“找不到帐户”错误。

Params are parsed as string by express middleware. 快速中间件将参数解析为string Say I make a req to path defined below like /some/1000 说我对下面定义的路径进行要求,例如/some/1000

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

So you need to parse the incoming parameter to integet since you've stored accountNumber as integer. 因此,由于您已将accountNumber存储为整数,因此您需要将传入参数解析为integet。 So adding toInt to chain like below should solve it: 因此,如下所示将toInt添加到链中应该可以解决该问题:

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

accountNumber inside accounts array is a number whereas req.params.accountNumber is a string. accounts数组中的accountNumber是一个数字,而req.params.accountNumber是一个字符串。 You need to convert the data type. 您需要转换数据类型。 You can do it as 你可以做到

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

I think that the problem is your query. 我认为问题在于您的查询。 find method runs in an asynchronous way, that's why isfound property does not contain the data you expect. find方法以异步方式运行,这就是为什么isfound属性不包含您期望的数据的原因。 Here is a simple approach using promises which works pretty well for me. 这是一种使用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();
    });

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM