[英]Why does fetch request have to be cloned in service worker?
在Google的一個Service Worker示例中, 緩存和返回請求
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
// IMPORTANT: Clone the request. A request is a stream and
// can only be consumed once. Since we are consuming this
// once by cache and once by the browser for fetch, we need
// to clone the response.
var fetchRequest = event.request.clone();
return fetch(fetchRequest).then(
function(response) {
// Check if we received a valid response
if(!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
// IMPORTANT: Clone the response. A response is a stream
// and because we want the browser to consume the response
// as well as the cache consuming the response, we need
// to clone it so we have two streams.
var responseToCache = response.clone();
caches.open(CACHE_NAME)
.then(function(cache) {
cache.put(event.request, responseToCache);
});
return response;
}
);
})
);
});
另一方面,MDN( 使用服務工作者)提供的示例不會克隆請求。
this.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(resp) {
return resp || fetch(event.request).then(function(response) {
caches.open('v1').then(function(cache) {
cache.put(event.request, response.clone());
});
return response;
});
}).catch(function() {
return caches.match('/sw-test/gallery/myLittleVader.jpg');
})
);
});
因此,對於Google示例中的緩存未命中情況:
我理解為什么我們必須克隆響應:因為它被cache.put
,我們仍然希望將響應返回給請求它的網頁。
但為什么要克隆請求呢? 在評論中,它表示它被緩存和瀏覽器用於獲取 。 這究竟是什么意思?
cache.put
? 如果是這樣,為什么caches.match
不會消耗請求? 在我看來,評論很清楚地說明為什么該代碼的作者認為克隆是必要的:
請求是一個流,只能被使用一次。 由於我們通過緩存消耗了一次,而瀏覽器一次用於獲取,我們需要克隆響應。
請記住,請求的body
可以是ReadableStream
。 如果cache.match
不得不讀取流(或部分讀取流)知道一個緩存條目是否匹配,通過后續讀fetch
將繼續寫有丟失任何數據cache.match
讀取。
如果它只在有限的情況下重要(除非Google示例中的代碼完全錯誤並且沒有必要),我不會感到驚訝,因此未能做到這一點可能適用於許多測試用例(例如,身體的位置)是null
或字符串,而不是流)。 請記住,MDN非常好,但它是社區編輯的,並且錯誤和不良示例會定期出現。 (這些年來我不得不修復幾個明顯的錯誤。)通常社區發現它們並修復它們。
fetch
請求,不會被緩存,因此caches
本質上不會消耗request
因此,無需克隆。 - 傑克先前寫過他的文章。
但是, responses
被put
或added
到緩存中和/或,可以作為JSON / text / something傳遞給then
鏈 - 意思是,它們是/可以被消費。
我的猜測是,如果你使用或改變某些東西,那么你需要克隆它。
read
可能在caches.match
都沒有
我也假設,可能另一個原因是,對請求本身的讀取不是通過piped
,並且只能通過caches.match
讀取一次,只讀一次,但響應流,可能是用其他變異/轉換/寫入管道進行管道傳輸
只是從流規格中抓住..但還要破譯一切如何加起來......也許我會把它留給權威人士
所以,如果我直到現在才解釋我的理解,克隆理想消費的東西 ,否則不要打擾。 在這種情況下,讀取本身不會改變請求/將其寫入別處,因此無需克隆
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.