XMLHttpRequest
Working With HTTP Headers
HTTP header fields carry metainformation describing the requested resource or reflecting the state of the established HTTP connection. Each header field consists of a name followed by a colon and the field value. General headers are applied both to request and response messages. These are
Cache-Control
Connection
Date
Pragma
Trailer
Transfer-Encoding
Upgrade
Via
Warning
Request headers contain additional information about the request as well as about the client that has generated the HTTP message. Standard request headers include the following:
Accept
Accept-Charset
Accept-Encoding
Accept-Language
Authorization
Expect
From
Host
If-Match
If-Modified-Since
If-None-Match
If-Range
If-Unmodified-Since
Max-Forwards
Proxy-Authorization
Range
Referer
TE
User-Agent
Entity headers display metainformation about the payload of an HTTP message or (in case there's no payload available) about the resource identified by the request URL:
Allow
Content-Encoding
Content-Language
Content-Length
Content-Location
Content-MD5
Content-Range
Content-Type
Expires
Last-Modified
Standard response headers pass additional information about the response, the server that has generated it, or defines the access rules for the requested resource:
Accept-Ranges
Age
ETag
Location
Proxy-Authenticate
Retry-After
Server
Vary
WWW-Authenticate
Web Author Request Headers
XMLHttpRequest API enables the customization of the headers created on the client side:
var xhr=new XMLHttpRequest();
xhr.open("GET", "http://example.com/");
xhr.setRequestHeader("X-Test-Header", "Test Value");
xhr.send();
The method setRequestHeader() allows the developer to emulate custom user agent behavior. However, some headers cannot be modified by the client script. The "protected" header fields are
Accept-Charset
Access-Control-Request-Headers
Access-Control-Request-Method
Accept-Encoding
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via
If a script-defined header name starts with Sec- or Proxy-, it is ignored by the user agent, too.
Response headers can be obtained by invoking the getAllResponseHeaders() method. In the example below, the HTTP HEAD method is used to collect metainformation about the requested Web resource. The resulting response does not contain any payload: only HTTP headers are sent to the client.
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=showResponseHeaders;
xhr.open("HEAD", "http://example.com/");
xhr.send();
. . .
function showResponseHeaders(event) {
if(event.target.readyState==4) {
if(event.target.status==200) {
console.log(event.target.getAllResponseHeaders());
}
}
}
Values of individual headers are retrieved by calling the getResponseHeader() method:
console.log("Server: "+event.target.getResponseHeader("Server"));