使用Swagger UI时添加标题

时间:2015-09-26 12:37:00

标签: javascript swagger swagger-ui

我的swagger.json文件(localhost:8000/rest/swagger.json)需要AuthType标头才能访问它的端点。如何在向swagger.json文件发出初始请求时让Swagger UI添加它?

到目前为止我已尝试过:

$(function () {
    var token = 'xxx';
    window.swaggerUi = new SwaggerUi({
        url: "http://" + location.host + "/rest/swagger.json",
        dom_id: "swagger-ui-container",
        supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
        onComplete: function (swaggerApi, swaggerUi) {
            var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("AuthToken", token, "header");
            window.swaggerUi.api.clientAuthorizations.add("AuthToken", apiKeyAuth);
            $('pre code').each(function (i, e) {
                hljs.highlightBlock(e)
            });
        },
        docExpansion: "none",
        apisSorter: "alpha",
        showRequestHeaders: false
    });

    swaggerUi.load();
});

但是,当我打开Chrome开发者工具并查看向localhost:8000/rest/swagger.json发出的请求时,它没有AuthType标头并且有401 Unauthorized响应。

注意:onComplete函数看起来似乎没有被调用(我猜测它之前请求swagger.json通常会被调用,因此它会落入{onFailure 1}}在请求失败时阻止)

2 个答案:

答案 0 :(得分:3)

我会告诉你我的情景。老实说,swagger的READ-ME不符合标准(这是我的看法)。他们没有提到有关向网址请求添加标头的任何内容。

我的用例是我必须调用我的API来获取 JSON响应。(我的API受 login_required 装饰器保护,这需要 xcsrf-token 将在标题中发送)

在您的情况下,您的 localhost:8000 / rest / swagger.json 类似于我的API。

如何解决此问题?

  1. 当我们 SwaggerUIBundle 时。一个名为“spec”的密钥(将在代码段后面解释 spec )必须与 JSON响应值。此 JSON响应 swagger-ui 页面提供了初始结构。
  2. 你在说什么?你在谈论什么样的用户界面? JSON响应的结构是什么?

    Click here for Swagger-UI example

    要使用swagger-ui创建此类型的页面,您需要为其提供JSON响应

    Click here for JSON reponse that you need to generate either using APIs or in your case ocalhost:8000/rest/swagger.json

    1. 使用AJAX请求调用您的API或 的本地主机:8000 /休息/ swagger.json

    2. 现在,在您的成功通话中, JSON 必须等同于“spec”

    3. 使用代码片段的说明

      1. 实例化 SwaggerUIBundle对象。请注意 spec 键,该键必须映射到 JSON响应值。 dom_id 可以是任何div的ID。
      2.   const ui = SwaggerUIBundle({
            spec: {},// put JSON response here.
            dom_id: '#swagger-ui',
            presets: [
              SwaggerUIBundle.presets.apis,
              // yay ES6 modules ↘
              Array.isArray(SwaggerUIStandalonePreset) ? SwaggerUIStandalonePreset : SwaggerUIStandalonePreset.default
            ],
            plugins: [
              SwaggerUIBundle.plugins.DownloadUrl
            ],
            layout: "StandaloneLayout"
          })
          window.ui = ui

        1. 现在在函数中包含此对象实例化。
        2. window.foo = function(spec){
            const ui = SwaggerUIBundle({
              spec: spec,
              dom_id: '#swagger-ui',
              presets: [
                SwaggerUIBundle.presets.apis,
                // yay ES6 modules ↘
                Array.isArray(SwaggerUIStandalonePreset) ? SwaggerUIStandalonePreset : SwaggerUIStandalonePreset.default
              ],
              plugins: [
                SwaggerUIBundle.plugins.DownloadUrl
              ],
              layout: "StandaloneLayout"
            })
            window.ui = ui
          }

          1. 让我们看看如何使用ajax调用来调用此函数。我们可以在AJAX调用期间添加任何令牌。
          2. window.onload = function() {
               function apiCall(uri, data, methodType) {
              const csrftoken = getCookie('csrftoken');
              //Add header to the URL . 
              $.ajaxSetup({
                beforeSend: function(xhr, settings) {
                  if (!this.crossDomain) {
                      xhr.setRequestHeader('X-CSRFToken', csrftoken);
                  }
                }
              });
              
              $.ajax({
                url: uri,
                method: methodType,
                contentType: 'application/json',
                data: data,
                success: function (response) {
                  var script = document.createElement('script');
                  // Calling the function which instantiates swaggerbundle object
                  foo(response)
                },
                error: function (error) {
                }
              });
            }
            
            
            // You can write your own getCookie function . 
            function getCookie(name) {
              let cookieValue = null;
              if (document.cookie && document.cookie !== '') {
                let cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                  let cookie = jQuery.trim(cookies[i]);
                  // Does this cookie string begin with the name we want?
                  if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                  }
                }
              }
              return cookieValue;
            }
              
              //['GET','POST'] 
              apiCall('http://localhost:8000/rest/swagger.json',{},'GET');
              
            }

            1. 这是最后的片段。
            2. window.foo = function(spec){
                const ui = SwaggerUIBundle({
                  spec: spec,
                  dom_id: '#swagger-ui',
                  presets: [
                    SwaggerUIBundle.presets.apis,
                    // yay ES6 modules ↘
                    Array.isArray(SwaggerUIStandalonePreset) ? SwaggerUIStandalonePreset : SwaggerUIStandalonePreset.default
                  ],
                  plugins: [
                    SwaggerUIBundle.plugins.DownloadUrl
                  ],
                  layout: "StandaloneLayout"
                })
                window.ui = ui
              }
              
              window.onload = function() {
                 function apiCall(uri, data, methodType) {
                const csrftoken = getCookie('csrftoken');
                //Add header to the URL . 
                $.ajaxSetup({
                  beforeSend: function(xhr, settings) {
                    if (!this.crossDomain) {
                        xhr.setRequestHeader('X-CSRFToken', csrftoken);
                    }
                  }
                });
                
                $.ajax({
                  url: uri,
                  method: methodType,
                  contentType: 'application/json',
                  data: data,
                  success: function (response) {
                    var script = document.createElement('script');
                    // Calling the function which instantiates swaggerbundle object
                    foo(response)
                  },
                  error: function (error) {
                  }
                });
              }
              
              
              // You can write your own getCookie function . 
              function getCookie(name) {
                let cookieValue = null;
                if (document.cookie && document.cookie !== '') {
                  let cookies = document.cookie.split(';');
                  for (let i = 0; i < cookies.length; i++) {
                    let cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                      break;
                    }
                  }
                }
                return cookieValue;
              }
                
                //['GET','POST'] 
                apiCall('http://localhost:8000/rest/swagger.json',{},'GET');
                
              }

答案 1 :(得分:1)

在您的示例中,您有window.swaggerUi,但尚未将swaggerApi变量分配给window对象。

尝试:

onComplete: function (swaggerApi, swaggerUi) {

    window.swaggerApi = swaggerApi;

    var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("AuthToken", token, "header");
    window.swaggerUi.api.clientAuthorizations.add("AuthToken", apiKeyAuth);
    $('pre code').each(function (i, e) {
        hljs.highlightBlock(e)
    });
}

第二:

虽然浏览器可能能够找到正确的swaggerUi变量尝试加载:

window.swaggerUi.load();

而不是:

swaggerUi.load();