roroinpho21
roroinpho21

Reputation: 742

XMLHttpRequest setRequestHeader for each request

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.

Upvotes: 11

Views: 45516

Answers (1)

Ganesh Kumar
Ganesh Kumar

Reputation: 3240

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.

Upvotes: 23

Related Questions