在没有 NodeJs 的客户端站点上使用带有 JavaScript 的 Swagger



如何在客户端站点上使用 Swagger 生成的 API 客户端源代码(没有 NodeJs 的普通浏览器应用程序(?

在第一次测试中,我使用 editor.swagger.io 为 Swaggers 的宠物商店 API (https://petstore.swagger.io/v2( 生成了一个 JavaScript 客户端

生成的代码包含一个索引.js该索引提供对公共 API 类的构造函数的访问,我尝试在我的 Web 应用程序中嵌入和使用它们。

该文档描述了 API 的用法,如下所示:

var SwaggerPetstore = require('swagger_petstore');
var defaultClient = SwaggerPetstore.ApiClient.instance;
// Configure API key authorization: api_key
var api_key = defaultClient.authentications['api_key'];
api_key.apiKey = 'YOUR API KEY';
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//api_key.apiKeyPrefix = 'Token';
var apiInstance = new SwaggerPetstore.PetApi();
var petId = 789; // Number | ID of pet to return

var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.getPetById(petId, callback);

这适用于 NodeJs 应用程序。但是,如何在浏览器中将API用于传统的客户端站点Web应用程序呢?对于此类应用程序,nodejs 函数所需的不起作用。

来自 https://github.com/swagger-api/swagger-js

该示例存在跨源问题,但它应该在您自己的项目中工作

<html>
<head>
<script src='//unpkg.com/swagger-client' type='text/javascript'></script> 
<script>
var specUrl = '//petstore.swagger.io/v2/swagger.json'; // data urls are OK too 'data:application/json;base64,abc...'
SwaggerClient.http.withCredentials = true; // this activates CORS, if necessary
var swaggerClient = new SwaggerClient(specUrl)
.then(function (swaggerClient) {
return swaggerClient.apis.pet.addPet({id: 1, name: "bobby"}); // chaining promises
}, function (reason) {
console.error("failed to load the spec" + reason);
})
.then(function(addPetResult) {
console.log(addPetResult.obj);
// you may return more promises, if necessary
}, function (reason) {
console.error("failed on API call " + reason);
});
</script>
</head>
<body>
check console in browser's dev. tools
</body>
</html>

最新更新