【问题标题】:How to add a custom header for every request in Swagger-UI version 3.0如何在 Swagger-UI 3.0 版中为每个请求添加自定义标头
【发布时间】:2017-07-13 15:41:12
【问题描述】:

我想在我的 swagger-ui 版本 3.0 上支持多个 json 版本。 每次ajax调用的第二个json我想添加一个自定义标头 名称为x-api-version,值为2

我试过这个:

$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('x-my-custom-header', 'some value');
    }
});

但它不起作用。 swagger ui 3.0.0的文档很差,找不到解决办法

【问题讨论】:

标签: swagger swagger-ui


【解决方案1】:

经过一些试验,如果 Swagger 使用 jquery 处理 OPTIONS 请求,而它使用 superagent 客户端 HTTP 请求库处理其他类型的请求,例如 GET、POST 等...

因此,要在 Swagger-UI 中为每个请求添加自定义标头,请使用以下代码:

    $(document).ready(function () {

    // Intercept jquery ajax request
    $.ajaxSetup({

        beforeSend: function (xhr, settings) {

            // Add the header to the Ajax request
            xhr.setRequestHeader("Authorization", getHeader());
        },

        // Disable caching of AJAX responses
        cache: false

    });

    // Intercept superagent request
    window.swaggerUi.options["requestInterceptor"] = function () {

        // Add the header to the request
        this.headers.Authorization = getHeader();

        return this;
    };

});

function getHeader() {

    var header = ... some code to calculate or generate a header ...

    return header
}

【讨论】:

    猜你喜欢
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 2017-07-09
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多