代码之家  ›  专栏  ›  技术社区  ›  Dave Sag

招摇过市验证器抱怨似乎格式良好的请求

  •  1
  • Dave Sag  · 技术社区  · 6 年前

    我用的是 swagger-express-validator 验证小型API服务器的输入(使用Swagger 2格式)

    path 定义如下

    /api/v1/users:
      post:
        produces:
          - "application/json"
        parameters:
          - in: body
            name: ids
            description: Array of user ids to be processed
            required: true
            schema:
              $ref: "#/definitions/ArrayOfIds"
        responses:
          200:
            description: success
    

    ArrayOfIds

    Id:
      type: string
    ArrayOfIds:
      type: array
      items:
        $ref: "#/definitions/Id"
    

    向服务器发送post请求,如下所示:

    POST /api/v1/users HTTP/1.1
    Content-Type: application/json
    Accept: application/json
    Host: localhost:3000
    Connection: close
    User-Agent: Paw/3.1.7 (Macintosh; OS X/10.13.6) GCDHTTPRequest
    Content-Length: 35
    
    {
      "ids": ["abcd12345"]
    }
    

    导致错误

    Request Invalid: POST /api/v1/users
     [ { keyword: 'type',
        dataPath: '',
        schemaPath: '#/type',
        params: { type: 'array' },
        message: 'should be array' } ]
    

    但是我可以访问 req.body.ids ['1234abc'] .

    你知道验证器为什么抱怨这个请求吗?我觉得很好。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Helen    6 年前

    您的请求正文与定义不匹配。根据定义,请求主体中的数组必须展开:

    POST /api/v1/users HTTP/1.1
    Content-Type: application/json
    ...
    
    ["abcd12345"]
    

    如果需要将数组包装到 ids type: object 与财产有关 包含数组的:

        parameters:
          - in: body
            name: ids
            description: Array of user ids to be processed
            required: true
            schema:
              type: object
              properties:
                ids:
                  $ref: "#/definitions/ArrayOfIds"