如何在 Swagger-UI 3.0 版中为每个请求添加自定义标头 [英] How to add a custom header for every request in Swagger-UI version 3.0

查看:119
本文介绍了如何在 Swagger-UI 3.0 版中为每个请求添加自定义标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to support multiple json versions on my swagger-ui version 3.0. The second json at every ajax call I want to add a custom header with name x-api-version and value 2

我试过这个:

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

但是它不起作用.swagger ui 3.0.0 的文档很差,我找不到解决方案

But it is not working. The documentation of swagger ui 3.0.0 is poor and I can't find a solution

推荐答案

经过一些试验,如果出现 Swagger 使用 jquery 进行 OPTIONS 请求的同时使用 superagent 客户端 HTTP 请求库,用于其他类型的请求,例如 GET、POST 等...

After some experimenting if appears that Swagger uses jquery for OPTIONS requests whilst it uses superagent client-side HTTP request library for other types of requests such as GET, POST etc...

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

Thus, to add a custom header for every request in Swagger-UI, use the following code:

    $(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
}

这篇关于如何在 Swagger-UI 3.0 版中为每个请求添加自定义标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆