简体   繁体   English

jQuery Ajax访问自定义响应头

[英]jQuery Ajax access custom response headers

I'm using some API, and I noticed that in the response I have this: 我正在使用一些API,我注意到在响应中我有这个:

Chrome控制台屏幕

I'd need to read the "x-dl-units-left", but I get null: 我需要阅读“x-dl-units-left”,但我得到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 谢谢

The issue is because the request is using CORS. 问题是因为请求正在使用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标头,例如:

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. 您需要从API提供商处请求它。

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"

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM