我正在使用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 /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' } ]
然而,我可以在我的Express路由器控制器代码中访问req.body.ids
,它包含正确的值['1234abc']
。
您是否知道验证者为什么抱怨该请求?它看起来很好。
您的请求正文与定义不符。根据定义,请求体中的数组必须打开:
POST /api/v1/users HTTP/1.1
Content-Type: application/json
...
["abcd12345"]
如果需要将数组包装到ids
包装器属性中,请求主体应定义为type: object
,其属性为包含数组的ids
:
parameters:
- in: body
name: ids
description: Array of user ids to be processed
required: true
schema:
type: object
properties:
ids:
$ref: "#/definitions/ArrayOfIds"