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.
The XMLHttpRequest method setRequestHeader() sets the value of an HTTP request header. When using setRequestHeader() , you must call it after calling open() , but before calling send() . If this method is called several times with the same header, the values are merged into one single request header.
setRequestHeader('Content-Type', 'application/json') ; is added 1 line above or below the Accept header, the method used changes to OPTIONS, the Accept header changes to "text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8" and the Content-Type header disappears as if it wasn't seen.
XMLHTTPRequest object is an API which is used for fetching data from the server. XMLHTTPRequest is basically used in Ajax programming. It retrieve any type of data such as json, xml, text etc. It request for data in background and update the page without reloading page on client side.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With