我正在使用swagger-API和swagger-editor为路由开发RESTful API。我不明白为什么我通过主体发送的JSON从未到达我的控制器。这是我的YAML
schemes:
- http
- https
produces: [application/json, multipart/form-data, application/x-www-form-urlencoded]
paths:
/projects:
x-swagger-router-controller: project
post:
description: create a new project
operationId: postProjects
consumes:
- application/json
parameters:
- name: param1
in: body
description: description
required: false
schema:
$ref: "#/definitions/Project"
responses:
"200":
description: Success
schema:
$ref: "#/definitions/Project"
default:
description: Error
schema:
$ref: "#/definitions/ErrorResponse"
definitions:
Project:
properties:
name:
type: string
required:
- name
我发送的邮件请求示例。
curl -v -X POST -H "Content-Type: application/json" -d '{"name":"test"}' http://127.0.0.1:10010/projects
以及响应
{"message":"Request validation failed: Parameter (param1) failed schema validation","code":"SCHEMA_VALIDATION_FAILED","failedValidation":true,"results":{"errors":[{"code":"OBJECT_MISSING_REQUIRED_PROPERTY","message":"Missing required property: name","path":[]}],"warnings":[]},"path":["paths","/projects","post","parameters","0"],"paramName":"param1"}
如果我将参数"name"设置为不需要,我只收到一个空的响应,如下所示{param1:{path:["path"、"/projects"、"post"、"parameters"one_answers"0"],架构:{name:"param1",in:'body',description:"description",required:false,schema:[Object]},originalValue:{},值:{}}我不知道为什么,因为其他格式,如标题、路径或表单数据都很好。我总是收到一个空的东西。req.swagger.params
没有值。我尝试了几种模式,但即使是最简单的也不起作用。我可以从标题中判断出"content-type":"application/json"。因此,设置了内容类型,模式将验证名为"name"的简单字符串参数。一切应该都会好起来的,但仍然不是。
此问题已修复。这与招摇无关。我用nodeJ构建了一个API,我意识到我没有中间件来处理body参数。因此,因为我错过了启用swagger中间件之前的一步,所以我无法对body参数执行任何操作。
在将json数据发送到API后端时获得空值的主要原因是您大多数时候给出的参数路径和您给出的参数命名。
您还必须明确声明您期望的模式类型
您必须将参数名称设置为body
并设置in: body
,以便它将主体对象选择为JSON
这里有一个例子。你可以试试
/auth/register:
post:
tags:
- Auth
parameters:
- in: body
name: user
description: Create a new user.
schema:
type: object
required:
- firstName
- lastName
- email
- password
- confirmPassword
properties:
firstName:
type: string
lastName:
type: string
email:
type: string
password:
type: string
confirmPassword:
type: string
example:
firstName: Jane
lastName: Doe
email: janedoe@gmail.com
password: pass
confirmPassword: pass
responses:
"200":
description: OK