【发布时间】:2017-06-01 17:01:43
【问题描述】:
我使用swagger脚本生成了一个rest api。
{
"swagger": "2.0",
...
},
"host": "localhost:8080",
"basePath": "/swagger-item-jaxrs",
"schemes": [ "http" ],
"consumes": [ "application/json" ],
"produces": [ "application/json" ],
"paths": {
"/item/{cd}": {
"get": {
"description": "Returns an item based on the item code passed.",
"operationId": "findItemById",
"produces": [
"application/json",
"application/xml",
"text/xml",
"text/html"
],
"parameters": [
{
"name": "cd",
"in": "path",
"description": "CD of item to fetch",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "item response",
"schema": {
"$ref": "#/definitions/item"
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/errorModel"
}
}
}
}
}
},
"definitions": {
"item": {
"type": "object",
"required": [
"cd",
"name"
],
"properties": {
"cd": {
"type": "string"
},
"name": {
"type": "string"
},
"tag": {
"type": "string"
}
}
},
"errorModel": {
"type": "object",
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
}
}
}
}
}
我可以使用客户端调用api生成java类,甚至可以在浏览器中输入url并得到响应。
浏览器:http://localhost:8080/swagger-item-jaxrs/item/0446840
回复:{"cd":"0446840","name":"ROYAL BASMATI RICE "}
Swagger UI 甚至可以得到相同的响应,并表明 curl 命令是:curl -X GET "http://localhost:8080/swagger-item-jaxrs/item/0446840" -H "accept: application/json"
我的 ajax 代码:
$.ajax({
url: "http://localhost:8080/swagger-item-jaxrs/item/0446840"
, method: "GET"
, headers: { "accept": "application/json" }
})
.done(function(data) {
alert('success');
console.log('success: ');
console.log(data);
})
.fail(function(err) {
console.log('error: ');
console.log(err);
});
Chrome 开发者工具控制台结果:
error:
Object {readyState: 0, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
任何帮助将不胜感激。
【问题讨论】: