【问题标题】:NodeJS Express nested input body object validationNodeJS Express 嵌套输入主体对象验证
【发布时间】:2019-01-23 14:21:06
【问题描述】:

我在使用“express-validator”包验证嵌套对象请求正文时遇到了一些问题。假设我们有一种方法可以使用这样的主体收集用户输入:

{
    "general": {
        "sessionId": "a2957207-e033-49e7-b9da-1c5f946a1074",
        "os": "android",
        "vendor": "htc"
    },
    "data": [
        {
            "target": "logPageVisits",
            "pageName": "users/packages",
            "engagementTime": 350
        }
    ]
}

express-validator 只提供这样的验证:

req.checkBody('engagementTime')
        .notEmpty()
        .withMessage('Engagement-Time is required')

似乎没有像这样验证嵌套对象的干净方法:

req.checkBody('data.engagementTime')
        .notEmpty()
        .withMessage('Engagement-Time is required')

我在Github 上发现了一个已关闭的问题!但这并不能满足我的担忧!

有更好的建议吗?

【问题讨论】:

  • 嘿,我遇到了同样的问题,但很难找到解决方案。你搞清楚了吗?
  • 嗨,最终我编写了自己的验证方法,它运行良好这里只是一个提示:if (typeof validationObject.field !== validationObject.filter) { validationErrors = ${validationObject.fieldName} 必须是 ${validationObject.filter}; } 的类型
  • 是的,可以。同时我正在尝试使用 checkSchema,看看它是否有趣。
  • 另外我忘了提到嵌套对象我必须使用 for 循环,我检查了输入变量的类型,如果是对象或数组,我会遍历元素。
  • 最后它工作得很好,我只是在写名字时出错了。实际上这是正文:{ payload: { identifier: 'xxxxx', type: false, data: { name: 'xxx' } } } 所以我只需要写 check('payload.data.name'), at首先我忘记了“有效载荷”

标签: javascript node.js validation express


【解决方案1】:

您始终可以为 express 创建自定义 middleware
例如,在您的情况下,非常简化它看起来像这样:

const checkNestedBodyMiddleware = (req, res, next) => {
  const { data } = req.body;

  // As I see, here is array in data, so we use simple find
  const engTimeInArr = data.find(d => d.engagementTime);

  if(!engTimeInArr){
    return res.status(400).send('Engagement-Time is required');
  }

  next();
}

然后在你的路由中使用它:

app.post('/some-route', checkNestedBodyMiddleware, (req, res) => {
   // your route logic here.
})

因此,在这种情况下,您将验证逻辑隐藏在中间件中,并且可以将任意数量的中间件分配给路由。

【讨论】:

    【解决方案2】:

    使用.*. 进行迭代

    req.checkBody('data.*.engagementTime')
             .notEmpty()
             .withMessage('Engagement-Time is required')
    

    【讨论】:

      【解决方案3】:

      我有点晚了,但这是从 v6.12.0 开始你可以做的事情。要验证架构,您可以使用checkSchema 方法:

      const { checkSchema } = require('express-validator');
      
      checkSchema({
        'general': {
          in: 'body', // the location of the field
          exists: {
            errorMessage: 'Field `general` cannot be empty',
            bail: true
          },
          isObject: {
            errorMessage: 'Field `general` must be an object',
            bail: true
          }
        },
        // to check a nested object field use `object.nestedField` notation
        'general.sessionId': {
          trim: true,
          isString: {
            errorMessage: 'Field `sessionId` must be a string',
            bail: true
          }
        },
        'data': {
          in: 'body', 
          exists: {
            errorMessage: 'Field `data` cannot be empty',
            bail: true
          },
          isArray: {
            errorMessage: 'Field `data` must be an array',
            bail: true
          }
        },
        // use `*` to loop through an array
        'data.*.engagementTime': { 
          notEmpty: {
            errorMessage: 'Field `engagementTime` should not be empty',
            bail: true
          }
        }
      })
      

      参考资料:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-29
        • 1970-01-01
        • 1970-01-01
        • 2021-04-15
        • 1970-01-01
        • 2019-04-14
        • 2011-03-21
        • 2018-02-27
        相关资源
        最近更新 更多