【问题标题】:Why does fetch request have to be cloned in service worker?为什么必须在 service worker 中克隆 fetch 请求?
【发布时间】:2018-01-19 00:20:26
【问题描述】:

在 Google 的一个 Service Worker 示例中,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 使用,我们仍然希望将响应返回给请求它的网页。

但是为什么必须克隆请求呢?在评论中它说它被 cache用于获取的浏览器 消耗。究竟是什么意思?

  • 请求流在缓存中的哪个位置被消耗? cache.put?如果是,为什么caches.match 不消费请求?

【问题讨论】:

    标签: javascript service-worker


    【解决方案1】:

    fetch 请求不会被缓存,因此caches 本质上不会消耗request

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

    但是,responsesputadded 进入缓存和/或,可以作为 JSON /text/ 其他东西沿 then 链向下传递 - 意思是,它们 / 可以被使用。

    我的猜测是,如果你使用mutate某些东西,那么你需要克隆它。

    read 可能在 caches.match 中都不做任何事情

    我还假设,可能另一个原因是,对请求本身的读取,不是piped 沿着链,并且只被caches.match 读取一次,如只读发生一次,但是响应流,可以通过管道传输到其他变异/转换/写入管道

    只是从流规范中掌握..尚未破译一切如何加起来..也许我会把它留给权威人士

    所以,如果我要解释我迄今为止的理解,请克隆理想情况下消费的内容,不要打扰其他内容。在这种情况下,读取本身不会改变请求/将其写入其他地方,因此无需克隆

    【讨论】:

      【解决方案2】:

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

      一个请求是一个流,只能被消费一次。由于我们通过缓存使用一次,浏览器使用一次进行获取,因此我们需要克隆响应。

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

      如果它只在有限的情况下很重要(除非 Google 示例中的代码完全错误并且没有必要),我不会感到惊讶,因此不这样做可能在许多测试用例中都有效(例如,其中正文是null 或字符串,而不是流)。请记住,MDN 非常好,但它社区编辑的,并且错误和糟糕的示例确实会定期出现。 (多年来,我不得不修复其中的几个明显错误。)通常社区会发现它们并修复它们。

      【讨论】:

      • google 开发者网络基础站点中的 sn-ps,在实现上有所不同。例如,Jake 不会克隆请求 here
      • @Schrodinger'scat:呵呵,但在代码下面说:“为了有效地使用内存,您只能读取一次响应/请求的正文。在上面的代码中,. clone() 用于创建可以单独读取的附加副本。"(注意 "...response/request's body once...")。我真的无法从服务人员的规范中看出,在我给它的几分钟内,你是否需要。我的猜测是,if 请求的主体是流。我可能会对其进行测试以确定(即便如此,我真的只知道它是否失败)。
      • hmm.. 好吧,而不是 service worker 规范,我猜这可能记录在缓存规范或 fetch api 规范中。需要阅读
      • @Schrodinger'scat:缓存由the service workers spec 覆盖。但我在该规范或它所指的streams 中找不到一个很好的可靠声明。
      • 我有一个问题,它说“.. 我们需要克隆响应。”但是为什么代码克隆请求?
      猜你喜欢
      • 1970-01-01
      • 2013-03-06
      • 1970-01-01
      • 2017-03-27
      • 2015-12-29
      • 2020-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多