Skip to content Skip to sidebar Skip to footer

Js/jquery Get Httprequest Request Headers?

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 po

Solution 1:

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 existif(!this.headers) {
        this.headers = {};
    }

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

    // Add the value to the headerthis.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'

Solution 2:

Something you could to is use Sinon's FakeXMLHttpRequest to replace your browser's XHR. It's described in this document on how to use it for testing but I'm pretty sure you can use the module for your debugging purposes.

What you need to do is:

var requests;
this.xhr = sinon.useFakeXMLHttpRequest();
this.xhr.onCreate = function(xhr) {
    requests.push(xhr);
}

And then later on, you can check your requests array for headers by:

console.log(requests[0].requestHeaders);

To access your request headers.

Post a Comment for "Js/jquery Get Httprequest Request Headers?"