Search code examples
javascriptjqueryajaxresponse-headersjqxhr

jQuery Ajax access custom response headers


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


Solution

  • 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.