开发者

How can I access the Content-Length header from a cross domain Ajax request?

开发者 https://www.devze.com 2023-02-07 10:48 出处:网络
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.

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"

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.

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"

I have e开发者_如何学Pythonxperimented with setting various headers in the preflighting or in the response, such as

Access-Control-Expose-Headers: 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?

(Chrome 8)


I was having the same problem, till I found a thread somewhere else that taught me to add this line on my .htaccess:

Header add Access-Control-Expose-Headers "Content-Length"

Then BOOM, it got fixed.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消