I've noticed that the results of and XMLHttpRequest.getResponseHeader()
don't always match the real headers returned (if the request is made in a regular manner).
For example, assume I'm making an xhr
request for https://foo.example.com/api/resource/100
. In Chrome's developer console, under 'Network', I can see the response being made -- I can also see all of the response headers (say, 10). However (copy-pasted console):
> response XMLHttpRequest > response.getAllResponseHeaders(); "content-type: text/html "
Are there any restrictions on what headers are available? Is this dependent on the response type? I remember getting a complete set of headers for 404s but just this one for 400s.
What gives?
The getResponseHeader() 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 the getAllResponseHeaders() method, which returns the entire raw header string.
In response to a cross-origin request, add 'Access-Control-Expose-Headers': '*' to your response header, so that all headers are available to be read in your client side code. You can also indicate which headers you want to expose by specifying the header names instead of a wildcard.
While you can't ready any headers of HTML response in JS, you can read Server-Timing header, and you can pass arbitrary key-value data through it.
The current state of standardizing the XMLHttpRequest API does only restrict the access to the Set-Cookie and Set-Cookie2 header fields:
client.getAllResponseHeaders()
Returns all headers from the response, with the exception of those whose field name is
Set-Cookie
orSet-Cookie2
.
Any other header field should be returned.
But as you’re doing a cross-origin request, the browser needs to implement XMLHttpRequest Level 2 as the original XMLHttpRequest does only allow same-origin requests:
The XMLHttpRequest Level 2 specification enhances the XMLHttpRequest object with new features, such as cross-origin requests […]
There you can read that the “Cross-Origin Resource Sharing specification filters the headers that filters the headers that are exposed by getResponseHeader() for non same-origin requests.”. And that specification forbids access to any response header field other except the simple response header fields (i.e. Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, and Pragma):
User agents must filter out all response headers other than those that are a simple response header […]
E.g. the
getResponseHeader()
method of XMLHttpRequest will therefore not expose any header not indicated above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With