我是使用 swagger-node (swagger-spec 2.0) 的新手,我需要我的 API 来使用和生成 XML 和 JSON(因为这是客户想要的)。目前我只关注“生产”部分。
在生成响应时,我知道我可以使用jstoxml或easyxml等工具将我的 js 对象转换为 XML 。所以问题是:在使用 swagger-node 时这是否必要,或者工具是否应该处理这个问题?我想我需要帮助我的控制器代码应该返回什么。
例如,使用 swagger 创建一个新项目
swagger project create myproject (choose express framework)
更改/hello
api 的 yaml 文件,以便get:
返回 json 或 xml
paths:
/hello:
# binds a127 app logic to a route
x-swagger-router-controller: hello_world
get:
description: Returns 'Hello' to the caller
# used as the method name of the controller
operationId: hello
produces:
- application/json
- application/xml
然后更改 hello_world.js 控制器以返回 json 对象而不是字符串
// variables defined in the Swagger document can be referenced using req.swagger.params.{parameter_name}
var name = req.swagger.params.name.value || 'stranger';
var hello = util.format('Hello, %s!', name);
// this sends back a JSON response which is a single string
res.json({message:hello});
}
当我启动项目并将 Postman 与 Header Accept = application/json 一起使用时,我得到了响应:
{
"message": "Hello, stranger!"
}
如果我更改 Header Accept application/xml
,我仍然会收到 JSON 响应,而不是 XML。我希望看到的是:
<object>
<message>Hello, stranger!</message>
</object>
我知道我的代码使用错误,res.json()
因为我相信它将 Content-Type 设置为application/json
.
我不知道还有什么可以用来生成 XML 响应。当我更改 res.json() 以使用 easyxml
var xml = easyxml.render({message:hello});
res.type('xml').end(xml);
然后我从 swagger 那里得到一个验证错误:
[
{
"status": 500,
"message": "Response validation failed: value expected to be an array/object but is not"
}
]
那么我的控制器应该如何格式化响应以返回 XML 或 JSON?