JS/jQuery get HTTPRequest request headers?

Lwyrn picture Lwyrn · May 9, 2012 · Viewed 49.5k times · Source

Using getAllResponseHeaders in the xhr object, is possible to get all the response headers after an ajax call. But I can't found a way to get the Request headers string, is that possible ?

Answer

Emil H picture Emil H · May 9, 2012

If this is for debugging purposes then you can just use Firebug or Chrome Developer Tools (and whatever the feature is called in IE) to examine the network traffic from your browser to the server.

An alternative would be to use something like this script:

$.ajax({
    url: 'someurl',
    headers:{'foo':'bar'},
    complete: function() {
        alert(this.headers.foo);
    }
});

However I think only the headers already defined in headers is available (not sure what happens if the headers are altered (for instance in beforeSend).

You could read a bit more about jQuery ajax at: http://api.jquery.com/jQuery.ajax/

EDIT: If you want to just catch the headers on all calls to setRequestHeader on the XMLHttpRequest then you can just wrapp that method. It's a bit of a hack and of course you would need to ensure that the functions wrapping code below is run before any of the requests take place.

// Reasign the existing setRequestHeader function to 
// something else on the XMLHtttpRequest class
XMLHttpRequest.prototype.wrappedSetRequestHeader = 
  XMLHttpRequest.prototype.setRequestHeader; 

// Override the existing setRequestHeader function so that it stores the headers
XMLHttpRequest.prototype.setRequestHeader = function(header, value) {
    // Call the wrappedSetRequestHeader function first 
    // so we get exceptions if we are in an erronous state etc.
    this.wrappedSetRequestHeader(header, value);

    // Create a headers map if it does not exist
    if(!this.headers) {
        this.headers = {};
    }

    // Create a list for the header that if it does not exist
    if(!this.headers[header]) {
        this.headers[header] = [];
    }

    // Add the value to the header
    this.headers[header].push(value);
}

Now, once the headers have been set on an XMLHttpRequest instance we can get them out by examining xhr.headers e.g.

var xhr = new XMLHttpRequest();
xhr.open('get', 'demo.cgi');
xhr.setRequestHeader('foo','bar');
alert(xhr.headers['foo'][0]); // gives an alert with 'bar'