10

I'm using some API, and I noticed that in the response I have this:

Chrome Console Screen

I'd need to read the "x-dl-units-left", but I get null:

$.ajax(ajaxConfig).done(function(response, textStatus, xhr){
  var left = xhr.getResponseHeader("x-dl-units-left"); //null
  var all = xhr.getAllResponseHeaders(); // "content-type: application/json;charset=UTF-8"
});

Anyone who might know why?? :(

Thank you

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Sampgun
  • 2,822
  • 1
  • 21
  • 38

2 Answers2

19

The issue is because the request is using CORS. Therefore you need to explicitly allow your custom headers to be exposed to the recipient. To do this add a Access-Control-Expose-Headers header to the response, eg:

Access-Control-Expose-Headers: x-dl-units-left, x-dl-units, [other headers as needed...]

Note that this must be done on the server that creates the response. If you do not have control of the server, then you will not be able to make this change. You would need to request it from the API provider.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Actually the API is not mine, so I can't edit those..But why I can see them in the browser if I can't access?? – Sampgun Sep 08 '17 at 09:53
  • And if I got this with php curl? – Sampgun Sep 08 '17 at 09:54
  • 1
    I added a note about that; you'll need to request the API provider to add the header - although it's rather odd they enabled CORS without adding the header to expose the custom headers. Probably just an oversight. The browser is allowed to see everything. JS cannot in this case because of the Same Origin Policy – Rory McCrossan Sep 08 '17 at 09:55
  • If you get it with cURL through PHP then it will work fine as CORS will not be an issue. – Rory McCrossan Sep 08 '17 at 09:55
  • 1
    Seeing them in the browser is different than what xhr can retrieve. cURL should retrieve all headers so that might be the best option. – mnewelski Sep 08 '17 at 09:55
  • Excellent. Thank you everybody! – Sampgun Sep 08 '17 at 09:56
5

Your access specifier isn't mentioned, and therefore it does stores but at somewhat unknown place. Now you need to initialise it first. For better initialisation :

IN RESPONSE

 Acccess-Control-Expose-Headers: x-dl-units-left;

ON CLIENT SIDE

 $.ajax(ajaxConfig).done(function(response, textStatus, xhr){

  var all = xhr.getAllResponseHeaders(); 
 // "content-type: application/json;charset=UTF-8"

});
Vikash Pathak
  • 3,444
  • 1
  • 18
  • 32
Asim Khan
  • 508
  • 1
  • 7
  • 21