javascript - "body"被锁定的响应不能用于响应请求

标签 javascript google-chrome service-worker

我只是在 google chrome 中尝试 service workers。我偶然发现了一个错误。 Googling the error gives one single result目前似乎在google chrome sourcecode .

我不相信错误是bug。当我在 firefox 中尝试时,出现内容损坏错误屏幕。它发生在我处理项目根目录的获取事件时:

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');
      })
  );
});

我不确定 body locked 错误是什么意思,所以我什至不知道相关代码是什么。

最佳答案

问题是响应的 body(实际内容,例如 HTML 或 JavaScript)只能用于某些目的一次,例如保存到缓存中或用作实际响应。

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

In fact, the main reason clone() exists is to allow multiple uses of Body objects (when they are one-use only.)

在这种情况下,问题在于将响应存储在缓存中然后将其返回。正确的做法是:

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

关于javascript - "body"被锁定的响应不能用于响应请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37747332/

相关文章:

javascript - jQuery AJAX - $.each 使用正确的数据重复 html 结构?

javascript - mocha api 测试 - PUT 路线

html - 在 Google Chrome for Mac 上将 CSS 中的输入按钮居中

javascript - 服务人员 : async await in combination with waituntil is not working properly

javascript - 使用 gulp 更新 serviceworker 配置

javascript - 如何抑制javascript异常?

javascript - Chrome 开发者工具 "Properties"部分如何帮助 CSS/JavaScript 开发?

javascript - 延迟长时间运行的计时器任务以提高滚动平滑度

javascript - 在没有 event.respondWith() 的情况下获取事件处理程序

javascript - 如何在 HTML 中获取元素的形状/多边形/边界路径/框架?