![](/img/trans.png)
[英]"Content-Length" header not included in response from service worker fetch
[英]How to get the content-length of the response from a request with fetch()
當我使用空響應主體執行請求時,我在返回response.json()
時遇到錯誤,因此我試圖在存在空主體時僅返回一個空對象。 我想要的方法是檢查響應的Content-Length
標頭,但是,不知何故response.headers.get('Content-Length')
以某種方式返回null
。 這是我的代碼:
function fetchJSON(url, options, state = null) {
return fetch(url, Object.assign({}, options, {
// TODO: Add options here that should be there for every API call
// TODO: Add token if there is one
}))
.then(response => {
// Pass the JSON formatted body to the next handler
if (response.ok === true) {
if (response.headers.get('Content-Length') === 0) return {};
return response.json();
}
// If the response was not an 2xx code, throw the appropriate error
if (response.status === 401) throw new AuthorizationError("You are not authorized to perform this action");
// If it is an error code that we did not expect, throw an regular error and hope that it gets noticed by
// a developer
throw new Error("Unexpected response: " + JSON.stringify(response));
});
}
您能否幫我找到響應的Content-Length
或幫我找到另一種方法?
服務器應在服務器端使用Access-Control-Expose-Headers 公開標頭:
Access-Control-Expose-Headers: Content-Length
@sideshowbarker 評論解釋了為什么您可以在瀏覽器的網絡面板中看到標題,但在您執行response.headers.get("Content-Length")
時收到null
:
僅僅因為您的瀏覽器收到標題並且您可以在 devtools 中看到標題並不意味着您的前端 JavaScript 代碼可以看到它。 如果來自跨域請求的響應沒有 Access-Control-Expose-Headers: Content-Length 響應 - 如本答案所示 - 那么是您的瀏覽器本身會阻止您的代碼訪問標頭. 對於跨域請求,如果 Access-Control-Expose-Headers 值包含該特定標頭的名稱,則您的瀏覽器只會向前端 JavaScript 代碼公開特定的響應標頭。
您可以通過將其復制/粘貼到控制台來查看它的工作情況:
fetch("//stackoverflow.com").then(response => console.log(response.headers.get("content-length")))
請注意, Headers.get的返回值將是一個字節串,因此您必須將其轉換為數字才能在數字表達式中使用它:
Number(response.headers.get("content-length")) > 0
我剛剛解決了我的問題,只需將response.json()
放在 try/catch-block 中並捕獲當我嘗試解析空主體時發生的錯誤。 這不是理想的解決方案,但它對我有用。
最后,您可以保持代碼干凈,只需編寫if (response.ok)
。
你可以這樣做:
if (response.ok === true) {
if (response.getResponseHeader("Content-Length") === 0) return {};
return response.json();
}
或者更容易像這樣:
if (response.ok === true) {
if (response.length === 0) return {};
return response.json();
}
你沒事吧? :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.