Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlHttpRequest getAllResponseHeaders() not returning all the headers

I'm trying to get the response headers from an ajax request but jQuery's getAllResponseHeaders xhr method only displays the "Content-Type" header. Anyone know why?

This is the response header
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:If-Modified-Since, Cache-Control, Content-Type, Keep-Alive, X-Requested-With, Authorization
Access-Control-Allow-Methods:GET, PUT, POST, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:1728000
Authorization:apikey="apikey1" AuthenticationToken="62364GJHGJHG"
Connection:keep-alive
Content-Length:240
Content-Type:application/json; charset=utf-8
X-Powered-By:Express

This is the success function

params.success = function (response, textStatus, jqXHR) {
  console.log(jqXHR.getAllResponseHeaders())
}

This is what it logs...
Content-Type: application/json; charset=utf-8

like image 717
screenm0nkey Avatar asked Jan 20 '12 17:01

screenm0nkey


People also ask

How to get response headers in XMLHttpRequest?

getAllResponseHeaders() 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.

Which method returns the specific header information?

The XMLHttpRequest method getResponseHeader() returns the string containing the text of a particular header's value.

What is Access Control expose headers?

The Access-Control-Expose-Headers response header allows a server to indicate which response headers should be made available to scripts running in the browser, in response to a cross-origin request. Only the CORS-safelisted response headers are exposed by default.


2 Answers

Just ran into this. It's because you're doing a CORS request and you're not exposing the Location header.

You need to add a Access-Control-Expose-Headers to your preflight CORS response in Express:

res.header('Access-Control-Expose-Headers', 'Content-Type, Location');
res.send(200);

That will solve the issue.

like image 194
Ben Lesh Avatar answered Oct 13 '22 13:10

Ben Lesh


according to the following

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers

The Access-Control-Expose-Headers response header indicates which headers can be exposed as part of the response by listing their names.

By default, only the 7 CORS-safelisted response headers are exposed:

Cache-Control
Content-Language
Content-Length
Content-Type
Expires
Last-Modified
Pragma

So this will work perfectly for all headers to be accessible and exposed

res.header('Access-Control-Expose-Headers', '*');
like image 38
Cloud-Lover Avatar answered Oct 13 '22 14:10

Cloud-Lover