服务工作进程 - 类型错误: 请求失败



我使用Service Worker 缓存来自其他域的资源。我收到此错误"类型错误:请求失败的服务工作者.js:12"我不知道为什么会发生此错误。

服务工作者.js

var cacheNames=['v1'];
var urlsToPrefetch=['file from other domain'];
self.addEventListener('install', function (event) {
event.waitUntil(
caches.open(cacheNames).then(function(cache) {
console.log('Service Worker: Caching Files');
cache.addAll(urlsToPrefetch.map(function (urlToPrefetch) {
console.log(urlToPrefetch);
return  new Request(urlToPrefetch, {mode: 'no-cors'});
})).catch(function(error){
console.log(error);
});
})
);
});
self.addEventListener('fetch', function(event) {
console.log('Service Worker: Fetching');
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});

这是处理不透明响应(使用mode: 'no-cors'获取的响应(的副作用。以下是这个较长答案的摘录:

开发人员可能会遇到不透明响应的一个"陷阱"涉及将它们与缓存存储 API 一起使用。两条背景信息是相关的:

  • 不透明响应的status属性始终设置为0,无论原始请求是成功还是失败。
  • 如果任何请求生成的响应的状态代码不在 2XX 范围内,则缓存存储 API 的add()/addAll()方法都将拒绝。

从这两点可以看出,如果作为add()/addAll()调用的一部分执行的请求导致响应不透明,则无法将其添加到缓存中。

可以通过显式执行fetch(),然后使用不透明响应调用put()方法来解决此问题。通过这样做,您有效地选择了您缓存的响应可能是服务器返回的错误的风险。

const request = new Request('https://third-party-no-cors.com/', {mode: 'no-cors'});
// Assume `cache` is an open instance of the Cache class.
fetch(request).then(response => cache.put(request, response));

最新更新