XMLHttpRequest setRequestHeader for each request
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.
roroinpho21
Updated on July 29, 2022Comments
-
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 setAuthorization 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 createXMLHttpRequest
objects the variablejwtoken
is already deleted. -
roroinpho21 over 8 yearsThanks, this really helped me. But I thought that it is possible to use something similar to
$.ajaxSetup beforeSend
.