jQuery Ajax access custom response headers

7.2k views Asked by At

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

2

There are 2 answers

6
Rory McCrossan On BEST ANSWER

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.

2
Asim Khan On

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"

});