简体   繁体   English

如何通过跨域 ajax 获得响应 header?

[英]How can I get response header via cross-domain ajax?

I'm trying to read documentation and I must confess it is not an easy reading.我正在尝试阅读文档,我必须承认这并不容易阅读。 I have no problem (after adding Access-Control-Allow-Origin header) to read responseText, but fail to get response header anywhere except Firefox.我没有问题(在添加 Access-Control-Allow-Origin 标头后)读取 responseText,但除了 Firefox 之外的任何地方都无法获得响应 header。

So, my question is what is the right way to get response header, using cross-domain ajax?所以,我的问题是使用跨域 ajax 获得响应 header 的正确方法是什么?

I've tried to use ( Access-Control-Expose-Headers ), but, again, failed to read header.我尝试使用( Access-Control-Expose-Headers ),但再次未能读取 header。

So the way it should work is that you specify the headers you want the client to have access to in the Access-Control-Expose-Headers header.因此,它应该工作的方式是在 Access-Control-Expose-Headers header 中指定您希望客户端可以访问的标头。 For example, if your server sets a Foo response header, and you want the client to be able to read it, your server should also send the following header:例如,如果您的服务器设置了 Foo 响应 header,并且您希望客户端能够读取它,您的服务器还应该发送以下 header:

Access-Control-Expose-Headers: Foo

On the client side, you can read all the response headers by calling xhr.getAllResponseHeaders().在客户端,您可以通过调用 xhr.getAllResponseHeaders() 来读取所有响应标头。 This returns the response headers as a string, which you can then parse into an object using the following code: https://gist.github.com/706839这会将响应标头作为字符串返回,然后您可以使用以下代码将其解析为 object: https://gist.github.com/7068

That is an explanation of how things should work.这是对事情应该如何运作的解释。 However, note that there is a bug in older browsers where the response headers can't be read on the client.但是,请注意,旧浏览器中存在一个错误,即无法在客户端上读取响应标头。 See here for more details: CORS xmlhttprequest HEAD method有关详细信息,请参见此处: CORS xmlhttprequest HEAD 方法

I had same problem, and found answer on Chromium mailing list that this is fixed in webkit, and it will be implemented in crhomium ~19.我有同样的问题,并在 Chromium 邮件列表上找到了答案,这是在 webkit 中修复的,它将在 crhomium ~19 中实现。

I will try to find topic and update my answer.我将尝试找到主题并更新我的答案。

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

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