我有一个 Web 应用程序,可将数据存储在浏览器中以支持“离线”工作。
以下是相关代码:
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');
});
}
});
}
});
}
上面的代码引发了这个 错误 :Uncaught (in promise) TypeError: Failed to execute 'put' on 'Cache': Partial response (status code 206) is unsupported
at service-worker.js
我对这个错误所做的研究提到清除缓存可以解决这个错误,但不幸的是它没有奏效。我非常感谢您帮助修复此错误。
最佳答案
您正在尝试存储状态代码为 206 的 Response 对象。这是 cache_storage 规范禁止的。请参阅此处的第 6 步:
https://w3c.github.io/ServiceWorker/#cache-put
206 状态代码表示仅响应正文的一部分已从服务器返回。通常,服务器仅在请求包含 Range
时才执行此操作标题。看:
What does the HTTP 206 Partial Content status message mean and how do I fully load resources?
您可以更改上面的代码以使用 Range
检查请求。 header ,然后创建一个没有违规 header 的新请求。这将导致将整个响应存储在 cache_storage 中,而不是尝试仅存储部分响应。由于您可以返回完整响应以满足范围请求,因此在您离线时应该可以正常工作。
关于javascript - Service Worker 无法在 'put' 上执行 'Cache',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66323598/