XMLHttpRequest setRequestHeader for each request

34,171

One way is to create a closure and pass the jwtoken to it when it is available. You can use the method returned by the closure to create a XMLHttpRequest object.

var customXMLHttpRequest = (function (jwtoken) {

    function getXMLHttpRequest(method, url, async){
        var xmlHttpRequest = new XMLHttpRequest();
        xmlHttpRequest.open(method, url, async);
        xmlHttpRequest.setRequestHeader('Authorization', 'Bearer ' + jwtoken);
        return xmlHttpRequest;
    }

    return getXMLHttpRequest;
})('Your token');

Here is how you can use this method to get a new XMLHttpRequest object.

var xmlHttpRequest = customXMLHttpRequest('post','http://www.yoursite.com',true);

This object will have the header set.

Another option is to save the token in the cookie and when creating XMLHttpRequest, use this value after retrieving it from cookie.

Share:
34,171
roroinpho21
Author by

roroinpho21

Updated on July 29, 2022

Comments

  • roroinpho21
    roroinpho21 almost 2 years

    The following code automatically sets Authorization request header for all jQuery Ajax requests:

    $.ajaxSetup({
        beforeSend: function(xhr) {
            xhr.setRequestHeader('Authorization', 'Bearer ' + jwtoken);
        }
    });
    

    I want something like above for all XMLHttpRequest objects created manually. More exactly the below request hasn't set Authorization header.

    var xhr = new XMLHttpRequest();
    xhr.file = $('myfile')[0].files[0];
    var fd = new FormData();
    fd.append('fileId', fileId);
    xhr.open('post','my-rote', true)
    xhr.send(fd);  
    

    I don't want to use xhr.setRequestHeader('Authorization', 'Bearer ' + jwtoken); beacuse when I create XMLHttpRequest objects the variable jwtoken is already deleted.

  • roroinpho21
    roroinpho21 over 8 years
    Thanks, this really helped me. But I thought that it is possible to use something similar to $.ajaxSetup beforeSend.