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)
Browser does not allow cross domain AJAX requests due to security issues. Cross-domain requests are allowed only if the server specifies same origin security policy. To enable CORS, You need to specify below HTTP headers in the server.
CORS is a mechanism that defines a procedure in which the browser and the web server interact to determine whether to allow a web page to access a resource from different origin. Figure 2. Cross domain ajax request. When you do a cross-origin request, the browser sends Origin header with the current domain value.
The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.
For a successful cross-domain communication, we need to use dataType “jsonp” in jquery ajax call. JSONP or “JSON with padding” is a complement to the base JSON data format which provides a method to request data from a server in a different domain, something prohibited by typical web browsers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With