错误:请求对象已被使用

Jul*_*hez 5 javascript node.js vue.js service-worker

我不断在控制台日志中收到此错误

未捕获(承诺中)类型错误:无法在“ServiceWorkerGlobalScope”上执行“获取”:无法使用已使用的请求对象构造请求。

我尝试更改我的 Service Worker 但不起作用

self.addEventListener('install', (event) => event.waitUntil(preLoad()));

const preLoad = function () {
  return caches.open('cc-offline').then((cache) => {
    return cache.addAll(['/offline.html', '/index.html']);
  });
}

self.addEventListener('fetch', (event) => {
  event.respondWith(checkResponse(event.request).catch(function () {
    return returnFromCache(event.request)
  }));
  event.waitUntil(addToCache(event.request));
});

const checkResponse = (request) => {
  return new Promise((fulfill, reject) => {
    fetch(request).then((response) => {
      (response.status !== 404) ? fulfill(response) : reject()
    }, reject)
  });
};

const addToCache = (request) => {
  return caches.open('cc-offline').then((cache) => {
    return fetch(request).then((response) => {
      return cache.put(request, response);
    });
  });
};

const returnFromCache = (request) => {
  return caches.open('cc-offline').then((cache) => {
    return cache.match(request).then((matching) => {
      return (!matching || matching.status == 404) ? cache.match('offline.html') : matching
    });
  });
};
Run Code Online (Sandbox Code Playgroud)

小智 3

fetch不允许您使用一个请求两次,至少在当前版本中是这样:)。在两者中使用相同的请求对象,checkResponse也许addToCache是这种情况。您可以在调用之前尝试克隆请求对象,fetch如此处所述为什么此代码无法执行“fetch”?

  • 您也无法克隆已使用的请求。如果响应正文已被使用,clone() 会抛出 TypeError。事实上,clone() 存在的主要原因是允许多次使用 Body 对象(当它们只能使用一次时)。` https://developer.mozilla.org/en-US/docs/Web/API/Request /克隆 (2认同)