23

After a jQuery.ajax() call jqXHR.getAllResponseHeaders() won't return all the headers. The server responded with the following headers:

Connection: keep-alive
Content-Length: 64
Content-Type: application/json
X-My-CustomHeader: whatever

getAllResponseHeaders() returned only:

Content-Type: application/json

What am I doing wrong?

Example

var request = {
  'url': 'http://api.someExternalDomain.com/resource/',
  'type': someMethod,
  'success': function(data, textStatus, jqXHR) {
    console.log(jqXHR.getAllResponseHeaders());
  }
};

$.ajax(request);
Kirby
  • 14,280
  • 7
  • 86
  • 100
Eddy Navarro
  • 231
  • 1
  • 2
  • 4

2 Answers2

12

svenyonson called this out in the comments, but for me it was the answer, so I'm elevating it. If you're doing CORS, the server has to be explicit about what headers the client is allowed to read. If you want to read X-My-CustomHeader in javascript, then this header should be in the server response:

Access-Control-Expose-Headers: X-My-CustomHeader

More detail here.

Chris
  • 5,980
  • 3
  • 33
  • 47
  • Documentation: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers – bmatovu Nov 15 '18 at 10:38
7

From jquery official website:

At present, due to a bug in Firefox where .getAllResponseHeaders() returns the empty string although .getResponseHeader('Content-Type') returns a non-empty string, automatically decoding JSON CORS responses in Firefox with jQuery is not supported.

http://api.jquery.com/jQuery.ajax/

Fabio Buda
  • 759
  • 2
  • 7
  • 16