'Service Worker Failed to execute 'put' on 'Cache'
I have a web app that stores the data in the browser to support working "offline".
Below is the code in concern:
function getPosCacheData(request, cacheName) {
var storageUrl = request.url;
var checkResponse = navigator.onLine;
return caches.open(cacheName).then(function(cache) {
if (checkResponse == true) {
return fetch(request).then(function(networkResponse) {
if (networkResponse.ok == true) {
cache.put(storageUrl, networkResponse.clone());
}
return networkResponse;
}).catch(function(error) {
return cache.match(storageUrl).then(function(response) {
if (response)
return formFilter(response);
else
return fallPosBackResponse('live');
});
});
} else {
return cache.match(storageUrl).then(function(response) {
if (response) {
return response;
} else {
return fetch(request).then(function(networkResponse) {
if(networkResponse.ok == true){
cache.put(storageUrl, networkResponse.clone());
}
return networkResponse;
}).catch(function(error) {
return fallPosBackResponse('css');
});
}
});
}
});
}
The code above raises this error:
Uncaught (in promise) TypeError: Failed to execute 'put' on 'Cache': Partial response (status code 206) is unsupported
at service-worker.js
The research I did about this error mentions that clearing the cache solves this error, but unfortunately it didn't work.
I do appreciate your kind help fixing this error.
Solution 1:[1]
You are trying to store a Response object with a status code of 206. This is forbidden by the cache_storage spec. See step 6 here:
https://w3c.github.io/ServiceWorker/#cache-put
A 206 status code indicates that only a part of the response body has been returned from the server. Normally a server only does this if the request included a Range
header. See:
What does the HTTP 206 Partial Content status message mean and how do I fully load resources?
You could change your code above to check for requests with a Range
header and then create a new request without the offending header. This will result in storing the entire response in cache_storage instead of trying to only store a partial response. Since you can return a full response to satisfy a range request this should work fine when you are offline.
Solution 2:[2]
fetch(event.request, {cache: "no-store"})
? Did the job for me.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ben Kelly |
Solution 2 | systrue |