Javascript 每个请求的 XMLHttpRequest setRequestHeader

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33545779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:13:27  来源:igfitidea点击:

XMLHttpRequest setRequestHeader for each request

javascriptjqueryajaxxmlhttprequest

提问by roroinpho21

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

以下代码Authorization request header为所有 jQuery Ajax 请求自动设置:

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

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

对于XMLHttpRequest手动创建的所有对象,我想要类似上面的内容。更确切地说,以下请求尚未设置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 XMLHttpRequestobjects the variable jwtokenis already deleted.

我不想xhr.setRequestHeader('Authorization', 'Bearer ' + jwtoken);在创建XMLHttpRequest对象时使用因为变量jwtoken已被删除。

回答by Ganesh Kumar

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.

一种方法是创建一个闭包,并在它可用时将 jwtoken 传递给它。您可以使用闭包返回的方法来创建 XMLHttpRequest 对象。

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.

以下是如何使用此方法获取新的 XMLHttpRequest 对象。

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.

另一种选择是将令牌保存在 cookie 中,并在创建 XMLHttpRequest 时从 cookie 中检索它后使用此值。