如何从一个跨域Ajax请求访问Content-Length头? [英] How can I access the Content-Length header from a cross domain Ajax request?

查看:2136
本文介绍了如何从一个跨域Ajax请求访问Content-Length头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JavaScript的应用程序需要在的决定资源的的长度与阿贾克斯下载。按说这是没有问题的,你只是做一个HEAD请求,并提取内容长度

My JavaScript application needs to determine the length of a resource before downloading it with Ajax. Ordinarily this is not a problem, you just make a HEAD request and extract the Content-Length.

var xhr = $.ajax({type:"HEAD", url: "http://own-domain/file.html"})
xhr.getResponseHeader("Content-Length")  
// "2195"

然而,资源存储在不同的服务器到客户机上。 (服务器I控制)。所以我使用CORS进行跨域Ajax请求,并成立了服务器响应preflighting请求HEAD请求和GET /自定义页眉POST请求。

However, the resources are stored on a different server to the client. (A server I control). So I'm using CORS to make cross domain ajax requests, and have set up the server to respond to preflighting requests for HEAD requests and GET/POST requests with custom headers.

这是伟大的工作为主,但我似乎无法找到一个方法提取内容长度从与CORS工作时,HEAD响应:

That is working great in the main, but I can't seem to find a way extract the Content-Length from the HEAD response when working with CORS:

var xhr = $.ajax({type:"HEAD", url: "http://other-domain/file.html"})
xhr.getResponseHeader("Content-Length")
// ERROR: Refused to get unsafe header "Content-Length"

我已经尝试了设置各种头在preflighting或反应,如

I have experimented with setting various headers in the preflighting or in the response, such as

Access-Control-Expose-Headers: Content-Length

其说明书似乎表明应使其可用。但无论我做什么,我似乎无法使Content-Length头提供给客户端。有什么建议?

which the specification seems to suggest should make it available. But no matter what I do, I can't seem to make the Content-Length header available to the client. Any suggestions?

(铬8)

推荐答案

我发现在所有浏览器CORS响应头的支持是马车。在Chrome浏览器/ Safari浏览器,我只看到getAllResponseHeaders的结果(简单的响应头(http://www.w3.org/TR/cors/#terminology)),即使在访问控制 - 暴露报头头被设置在响应中。而在Firefox 3.6.13,getAllResponseHeaders()不返回任何东西(甚至不是简单的响应头)。作为一种变通方法,我想你可以重载简单的响应头之一包括内容长度,但是这可能会导致其他问题,仍然不会解决Firefox浏览器。

I've found CORS response header support in all browsers to be buggy. In Chrome/Safari, I only see simple response headers (http://www.w3.org/TR/cors/#terminology) in the result of getAllResponseHeaders(), even when the "Access-Control-Expose-Headers" header is set in the response. And in Firefox 3.6.13, getAllResponseHeaders() doesn't return anything (not even simple response headers). As a workaround, I suppose you could overload one of the simple response headers to include the content-length, but that may cause other issues, and still wouldn't fix Firefox.

这篇关于如何从一个跨域Ajax请求访问Content-Length头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆