The XMLHttpRequest
method getAllResponseHeaders()
returns all the response headers, separated by CRLF, as a string, or returns null
if no response has been received.
If a network error happened, an empty string is returned.
Note: For multipart requests, this returns the headers from the current part of the request, not from the original channel.
Syntax
Parameters
Return value
A string representing all of the response's headers (except those whose field name is Set-Cookie
) separated by CRLF, or null
if no response has been received. If a network error happened, an empty string is returned.
An example of what a raw header string looks like:
Each line is terminated by both carriage return and line feed characters (\r\n
). These are essentially delimiters separating each of the headers.
Note: In modern browsers, the header names are returned in all lower case, as per the latest spec.
Examples
This example examines the headers in the request's readystatechange
event. The code shows how to obtain the raw header string, as well as how to convert it into an array of individual headers and then how to take that array and create a mapping of header names to their values.
const request = new XMLHttpRequest();
request.open("GET", "foo.txt", true);
request.send();
request.onreadystatechange = () => {
if (request.readyState === this.HEADERS_RECEIVED) {
const headers = request.getAllResponseHeaders();
const arr = headers.trim().split(/[\r\n]+/);
const headerMap = {};
arr.forEach((line) => {
const parts = line.split(": ");
const header = parts.shift();
const value = parts.join(": ");
headerMap[header] = value;
});
}
};
Once this is done, you can, for example:
const contentType = headerMap["content-type"];
This obtains the value of the Content-Type
header into the variable contentType
.
Specifications
Browser compatibility
|
Desktop |
Mobile |
|
Chrome |
Edge |
Firefox |
Internet Explorer |
Opera |
Safari |
WebView Android |
Chrome Android |
Firefox for Android |
Opera Android |
Safari on IOS |
Samsung Internet |
getAllResponseHeaders |
1 |
12 |
1Starting from Firefox 49, empty headers are returned as empty strings in case the preference network.http.keep_empty_response_headers_as_empty_string is set to true , defaulting to false . Before Firefox 49 empty headers had been ignored. Since Firefox 50 the preference defaults to true .
|
5 |
≤12.1 |
1.2 |
4.4 |
18 |
4Starting from Firefox 49, empty headers are returned as empty strings in case the preference network.http.keep_empty_response_headers_as_empty_string is set to true , defaulting to false . Before Firefox 49 empty headers had been ignored. Since Firefox 50 the preference defaults to true .
|
≤12.1 |
1 |
1.0 |
lowercase |
60 |
79 |
64 |
No |
47 |
11 |
60 |
60 |
64 |
44 |
11 |
8.0 |
See also