"身体"被锁定的响应不能用于响应请求

Tom*_*ica 8 javascript google-chrome service-worker

我只是在谷歌浏览器中尝试服务工作者.我偶然发现了一个错误.谷歌搜索错误提供了一个单一的结果,似乎在谷歌铬源代码中.

我不相信错误是错误的.当我在firefox中尝试时,我收到了Corrupted Content Error屏幕.当我处理项目根的fetch事件时会发生这种情况:

self.addEventListener('fetch', function(event) {
  // Nice url
  var requestURL = new URL(event.request.url);
  console.log("Request for: ", requestURL.href);
  // Network, then cache, then fallback
  event.respondWith(
    // Try to download
    fetch(event.request)
      .then(function(x) {
        console.log("    "+requestURL.href+" >> ",x);
        // If failed the x will not be ok
        if(x && x.ok) {
          // If result was ok save it to cache
          cache.put(event.request, x);
          return x;
        }
        else
          // Try to fetch cached version if request failed
          return cache.match(event.request);
      })
      // In case of error return something like 404 page
      .catch(function(error) {
        console.warn("    "+requestURL.href+" >> UNAVAILABLE: ",error);
        return cache.match('/page/content-not-available-offline');
      })
  );
});
Run Code Online (Sandbox Code Playgroud)

我不确定身体锁定错误意味着什么,所以我甚至不知道什么代码是相关的.

Tom*_*ica 13

问题在于body响应(实际内容,例如HTML或JavaScript)只能用于某些目的,例如保存到缓存或使用实际响应.

为了解决这个问题,Response.prototype.clone()存在方法.

实际上,clone()存在的主要原因是允许多次使用Body对象(当它们只是一次使用时.)

在这种情况下,问题是将响应存储在缓存中然后返回它.正确的方法是:

if(x && x.ok) {
  // If result was ok save it to cache
  cache.put(event.request, x.clone());
  return x;
}
Run Code Online (Sandbox Code Playgroud)