Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 278
roroinpho21 Avatar asked Nov 05 '15 13:11

roroinpho21


People also ask

What is the correct way to use setRequestHeader?

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.

How can request content type be set to XML via XMLHttpRequest?

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.

What is the use of XMLHttpRequest object explain methods that are used to send request to server using Ajax?

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.


1 Answers

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.

like image 169
Ganesh Kumar Avatar answered Sep 20 '22 07:09

Ganesh Kumar