0

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

I tried this one:

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

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

Giannis Grivas
  • 3,374
  • 1
  • 18
  • 38
  • This is currently not supported in 3.x. See the discussion at https://github.com/swagger-api/swagger-ui/issues/2793. – Helen Jul 13 '17 at 18:45
  • Possible duplicate of [swagger-ui 3.0.6 - Add custom authorization header client side](https://stackoverflow.com/q/43495263/113116) – Helen Jul 13 '17 at 18:47

1 Answers1

0

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...

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
}