首页 文章

为什么必须在服务工作者中克隆获取请求?

提问于
浏览
8

在Google的一个服务工作者示例中,cache and return requests

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提供的示例Using Service Workers不会克隆请求 .

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 消耗了,我们仍然希望将响应返回给请求它的网页 .

但为什么要克隆请求呢?在评论中,它表示它被 cachethe browser for fetch 消耗 . 这究竟是什么意思?

  • 缓存中的哪个位置消耗了请求流? cache.put ?如果是这样,为什么 caches.match 不会消耗该请求?

2 回答

  • 2

    在我看来,评论很清楚地说明为什么该代码的作者认为克隆是必要的:

    请求是一个流,只能被使用一次 . 由于我们通过缓存消耗了一次,而浏览器一次用于获取,我们需要克隆响应 .

    请记住,请求的body可以是ReadableStream . 如果 cache.match 必须读取流(或部分读取流)以了解缓存条目是否匹配,则 fetch 的后续读取将继续读取,从而丢失任何 cache.match 读取的数据 .

    我不希望这样做,因此未能做到这一点可能适用于许多测试用例(例如,正文是 null 或字符串,而不是流) . 请记住,MDN非常好,但它是社区编辑的,并且错误和不良示例会定期出现 . (这些年来我不得不修复几个明显的错误 . )通常社区发现它们并修复它们 .

  • 0

    fetch 请求,没有缓存,因此 caches 基本上不消耗 request

    因此,无需克隆 . - asked Jake on his write up earlier.

    然而, responsesputadded 进入缓存和/或,可以作为JSON / text / something传递到 then 链 - 意思是,它们/可以被消耗 .

    我的猜测是,如果你是 usemutate 那么,你需要克隆它 .

    read 可能在 caches.match 中都没有

    我也假设,可能是另一个原因是,对请求本身的读取不是在链下面,并且只被 caches.match 读取一次,因为只读,只读一次,但响应流可以通过管道输入其他变异/转换/写入管道

    只是从流规格中 grab ..但还要破译一切如何加起来......也许我会把它留给权威人士

    所以如果我直到现在才解释我的理解,那么克隆一下理想的情况并不要打扰 . 在这种情况下,读取本身不会改变请求/将其写入别处,因此无需克隆

相关问题