【问题标题】:Error: Request object that has already been used错误:请求对象已被使用
【发布时间】:2019-05-04 05:58:42
【问题描述】:

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

未捕获(承诺中)类型错误:无法在“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
    });
  });
};

【问题讨论】:

    标签: javascript node.js vue.js service-worker


    【解决方案1】:

    fetch 不允许您使用请求两次,至少在当前版本中:)。在checkResponseaddToCache 中使用相同的请求对象可能就是这种情况。您可以在调用fetch 之前尝试克隆请求对象,如Why does this code fail to execute 'fetch'? 中所述

    【讨论】:

    • 我现在收到了:Uncaught (in promise) TypeError: Failed to execute 'clone' on 'Request': Request body is already used
    • 您也无法克隆已使用的请求。 clone() throws a TypeError if the response Body has already been used. In fact, the main reason clone() exists is to allow multiple uses of Body objects (when they are one-use only.)developer.mozilla.org/en-US/docs/Web/API/Request/clone
    • any 导致解决 Uncaught (in promise) TypeError: Failed to execute 'clone' on 'Request': Request body is already used
    猜你喜欢
    • 2023-01-19
    • 1970-01-01
    • 2019-05-29
    • 2015-06-08
    • 1970-01-01
    • 2021-09-11
    • 2018-05-18
    • 1970-01-01
    • 2019-08-25
    相关资源
    最近更新 更多