jQuery jqXHR.getAllResponseHeaders() 不会返回所有标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5614735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:29:49  来源:igfitidea点击:

jqXHR.getAllResponseHeaders() won't return all headers

ajaxjquery

提问by Eddy Navarro

After a jQuery.ajax()call jqXHR.getAllResponseHeaders()won't return all the headers. The server responded with the following headers:

jQuery.ajax()通话后jqXHR.getAllResponseHeaders()不会返回所有标题。服务器响应以下标头:

Connection: keep-alive
Content-Length: 64
Content-Type: application/json
X-My-CustomHeader: whatever

getAllResponseHeaders()returned only:

getAllResponseHeaders()仅返回:

Content-Type: application/json

What am I doing wrong?

我究竟做错了什么?

Example

例子

var request = {
  'url': 'http://api.someExternalDomain.com/resource/',
  'type': someMethod,
  'success': function(data, textStatus, jqXHR) {
    console.log(jqXHR.getAllResponseHeaders());
  }
};

$.ajax(request);

回答by Chris

svenyonson called this out in the comments, but for me it was the answer, so I'm elevating it. If you're doing CORS, the server has to be explicit about what headers the client is allowed to read. If you want to read X-My-CustomHeaderin javascript, then this header should be in the server response:

svenyonson 在评论中指出了这一点,但对我来说,这就是答案,所以我在提升它。如果您正在执行 CORS,则服务器必须明确说明允许客户端读取哪些标头。如果你想X-My-CustomHeader在 javascript 中阅读,那么这个标头应该在服务器响应中:

Access-Control-Expose-Headers: X-My-CustomHeader

More detail here.

更多细节在这里

回答by Fabio Buda

From jquery official website:

来自jquery官网:

At present, due to a bug in Firefox where .getAllResponseHeaders() returns the empty string although .getResponseHeader('Content-Type') returns a non-empty string, automatically decoding JSON CORS responses in Firefox with jQuery is not supported.

目前,由于 Firefox 中的错误,其中 .getAllResponseHeaders() 返回空字符串,尽管 .getResponseHeader('Content-Type') 返回非空字符串,则不支持在 Firefox 中使用 jQuery 自动解码 JSON CORS 响应。

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/jQuery.ajax/