当前位置: 动力学知识库 > 问答 > 编程问答 >

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

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: