0
votes

I use clone() to create a clone of a response object. Then store it into the cache storage. But I got error message when service worker want to store the response of fetch result. Do I use the service worker or clone the response in a wrong way?

Error message I got:

Uncaught (in promise) TypeError: Failed to execute 'clone' on 'Response': Response body is already used

screen shot: here

Here is part of my code:

self.addEventListener("fetch", function(event) {
  // Get asset from cacheStorage first.
  // If it's not cached. Fetch it and cache it.
  event.respondWith(
    caches.match(event.request).then(function(cachedResponse) {
      return (
        cachedResponse ||
        fetch(event.request).then(function(fetchedResponse) {
          console.log(event.request.url);
          caches.open(cacheVersion).then(function(cache) {
            cache.put(event.request, fetchedResponse.clone());
          });

          return fetchedResponse;
        })
      );
    })
  );
}

The entire code: https://github.com/wtlin1228/service-worker/tree/master

1

1 Answers

0
votes

I think return is getting called before execution of fetch So following error is getting returned.

 fetch(event.request).then(function(fetchedResponse) {
          let fetchedResponses = fetchedResponse.clone();
          caches.open(cacheVersion).then((cache) => {
              cache.put(event.request, fetchedResponses);
          });

          return fetchedResponse;
        })