首页 > 解决方案 > 如何正确发送参数和标头以获取 swagger 客户端?

问题描述

目前正在查看https://www.npmjs.com/package/swagger-client。文档让我有点困惑。

我打算点击类似的网址www.mysite.com/topic/:topicName

我尝试了一些这样的事情:

  const authHeaders = {
    'X-Api-Key': 'mykey',
    Authorization: `Bearer mytoken`,
  };
  const topic = await client.apis.Topic.getTopic({
    headers: authHeaders,
    parameters: {
      topicName: 'myName'
    }
  });

我似乎无法找到正确的方法来发送标头并从 swagger 文档中填写变量以形成 URL。我见过标题是第一个参数的例子,所以我也试过

  const topic = await client.apis.Topic.getTopic(authHeaders, {
    parameters: {
      topicName: 'myName'
    }
  });

当我查看单词标题的文档时,他们只是谈论设置初始客户端。我认为让它每次都发送身份验证标头是另一个很好的解决方案,所以我正在寻找两种方式(因为根据标头,任何一种都有意义)。

标签: node.jsswagger

解决方案


使用 swagger-client 与常规 http 客户端略有不同,因为它完全遵循您的 swagger 文件,您必须提供您的 swagger 规范描述的参数。对于 swagger 客户端 v3,这种格式适用于我:

Swagger({ 
  url: "www.example.org/swagger.json",
  authorization: {
    // This must be described in your swagger file, if not, will be ignored.
    // See https://swagger.io/docs/specification/authentication/bearer-authentication/
    bearerAuth: {type: 'apiKey', 'in': 'header', name: 'Authorization'}
  }
}).then(client => {
  client.apis.Topic.getTopic({
    // The parameters need to be described in the swagger file, or will be ignored.
    // Also make sure that the getTopic operation describes that uses the bearerAuth
    // Or swagger-client will not send the Auth credentials.
    topicName: "myName"
  }).then(response => {
    // Do magic.
  })
});

您的 getTopic 操作的招摇部分应与此类似:

{
  "/rest/3/topic/{topicName}": {
    "tags": ["topic"]
    "operationId": "getTopic"
    "get": {
      "parameters": [
        {
          "name": "topicName", "in": "path", "required": true, "type": "string"
        } 
      ],
      "security": { "basicAuth": "global" }
    }
  }
}

推荐阅读