我有一个招摇的应用程序,当返回JSON时有效,但不适用于JSONP。成功和失败案例将进一步描述。
值得注意的是,下面显示的确切控制器代码在vanilla node / express下工作正常 - 当响应通过swagger响应验证器时,问题似乎就出现了。
处理响应的控制器代码片段如下:
retVal.success = true;
retVal.data = jsondata;
res.set('Content-Type', 'application/javascript');
res.jsonp(200, retVal);
swagger.yaml:
swagger: "2.0"
info:
title: sometitle
version: v1
host: localhost:3000
basePath: /
schemes:
- http
consumes:
- application/json
- application/javascript
produces:
- application/json
- application/javascript
- text/javascript
paths:
/loadallrepos:
x-swagger-router-controller: loadallrepos
get:
summary: summary here...
description: |
description here...
operationId: loadallrepos
parameters:
- name: callback
in: query
description: Passed by .ajax call for cross-domain requests
required: false
type: string
responses:
200:
description: Success
schema:
$ref: "#/definitions/loadallreposResponse"
definitions:
loadallreposResponse:
type: object
required:
- success
- data
properties:
success:
type: boolean
data:
type: object
required:
- nextrefresh
properties:
nextrefresh:
type: integer
如果我在没有callback参数的情况下发出请求,则可以:
请求:localhost:3000 / loadallrepos
响应:
{
"success": true,
"data": {
"nextrefresh": 3439704
}
}
如果我把它变成jsonp请求,它会失败:
请求:localhost:3000 / loadallrepos?callback = jQuery111106460774131119251_1439402109118& _1439402109119
响应:
{
"message": "Response validation failed: value expected to be an array/object but is not",
"failedValidation": true,
"originalResponse": "typeof jQuery111106460774131119251_1439402109118 === 'function' && jQuery111106460774131119251_1439402109118({
"success": true,
"data": {
"nextrefresh": 3442750
}
});"
}
同样,这在vanilla node / express下工作。非常感谢任何帮助!
答案 0 :(得分:3)
JSONP API返回一串JavaScript。您的Swagger定义表明您的API会返回#/definitions/loadallreposResponse
定义的对象type
object
。结果是swagger-node / swagger-tools看到type
object
并试图在响应主体上使用JSON.parse
并失败。要使用Swagger支持JSONP,您需要使响应模式为type
string
,以避免响应验证失败。