XMLHttpRequest: getResponseHeader() method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Note: This feature is available inWeb Workers, except forService Workers.
TheXMLHttpRequest methodgetResponseHeader() returns the string containing thetext of a particular header's value.
If there are multiple response headerswith the same name, then their values are returned as a single concatenated string,where each value is separated from the previous one by a pair of comma and space. ThegetResponseHeader() method returns the value as a UTF byte sequence.
Note:The search for the header name is case-insensitive.
If you need to get the raw string of all of the headers, use thegetAllResponseHeaders() method,which returns the entire raw header string.
In this article
Syntax
getResponseHeader(headerName)Parameters
headerNameA string indicating the name of the header you want to return thetext value of.
Return value
A string representing the header's text value, ornullif either the response has not yet been received or the header doesn't exist in theresponse.
Examples
In this example, a request is created and sent, and areadystatechangehandler is established to look for thereadyStateto indicate that the headers have been received; when that is the case,the value of theContent-Type header is fetched. If theContent-Type isn't the desired value, theXMLHttpRequest iscanceled by callingabort().
const client = new XMLHttpRequest();client.open("GET", "unicorns-are-awesome.txt", true);client.send();client.onreadystatechange = () => { if (client.readyState === client.HEADERS_RECEIVED) { const contentType = client.getResponseHeader("Content-Type"); if (contentType !== myExpectedType) { client.abort(); } }};Specifications
| Specification |
|---|
| XMLHttpRequest> # dom-xmlhttprequest-getresponseheader> |
Browser compatibility
See also
- Using XMLHttpRequest
- HTTP headers
getAllResponseHeaders()response- Setting request headers:
setRequestHeader()