jQuery Ajax access custom response headers
Asked Answered
W

2

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

Watchmaker answered 8/9, 2017 at 9:46 Comment(2)
Thx 4 the edit Rory :) I forgot to press Ctrl+K :DWatchmaker
This answer seems to explain the problem quite well.Lulualaba
C
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.

Caplin answered 8/9, 2017 at 9:51 Comment(6)
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??Watchmaker
And if I got this with php curl?Watchmaker
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 PolicyCaplin
If you get it with cURL through PHP then it will work fine as CORS will not be an issue.Caplin
Seeing them in the browser is different than what xhr can retrieve. cURL should retrieve all headers so that might be the best option.Lulualaba
Excellent. Thank you everybody!Watchmaker
R
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"

});
Radiotelegraphy answered 8/9, 2017 at 10:7 Comment(2)
I'll try this asapWatchmaker
You just need to declare and get value for left outside your function.Radiotelegraphy

© 2022 - 2024 — McMap. All rights reserved.