問題描述
我的 JavaScript 應用程序需要在使用 Ajax 下載資源之前確定資源的長度.通常這不是問題,您只需發出 HEAD 請求并提取 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"
但是,資源存儲在與客戶端不同的服務器上.(我控制的服務器).所以我使用 CORS 來發出跨域 ajax 請求,并設置服務器來響應 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 響應中提取 Content-Length
的方法:
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
規范似乎建議應該使其可用.但無論我做什么,我似乎都無法使 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),即使是Access-Control-Expose-Headers"標頭在響應中設置.在 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 標頭?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!