在没有NodeJs的客户端站点上使用Swagger和javascript

问题描述 投票:0回答:1

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

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

生成的代码包含一个index.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​​用于传统的客户端网站应用程序?对于此类应用程序,nodejs函数require不起作用。

javascript node.js browser client swagger
1个回答
1
投票

来自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>
© www.soinside.com 2019 - 2024. All rights reserved.