Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 471
Sampgun Avatar asked Sep 08 '17 09:09

Sampgun


Video Answer


2 Answers

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.

like image 170
Rory McCrossan Avatar answered Oct 19 '22 22:10

Rory McCrossan


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"

});
like image 3
Asim Khan Avatar answered Oct 19 '22 22:10

Asim Khan