Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

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

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 experimented 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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...