问题描述
我开始学习PWA(渐进式Web应用程序),但遇到问题,控制台抛出"错误未捕获(答应)TypeError:无法获取.
I started learning PWA (Progressive Web App) and I have problem, console "throws" error Uncaught (in promise) TypeError: Failed to fetch.
有人知道是什么原因吗?
Anyone know what could be the cause?
let CACHE = 'cache';
self.addEventListener('install', function(evt) {
console.log('The service worker is being installed.');
evt.waitUntil(precache());
});
self.addEventListener('fetch', function(evt) {
console.log('The service worker is serving the asset.');
evt.respondWith(fromCache(evt.request));
});
function precache() {
return caches.open(CACHE).then(function (cache) {
return cache.addAll([
'/media/wysiwyg/homepage/desktop.jpg',
'/media/wysiwyg/homepage/bottom2_desktop.jpg'
]);
});
}
function fromCache(request) {
return caches.open(CACHE).then(function (cache) {
return cache.match(request).then(function (matching) {
return matching || Promise.reject('no-match');
});
});
}
推荐答案
我认为这是由于您没有后备策略而引起的. event.respondWith
带有一个承诺,如果出现错误,您必须抓住这个承诺.
I think this is due to the fact that you don't have a fallback strategy. event.respondWith
comes with a promise which you have to catch if there's some error.
因此,我建议您从此更改代码:
So, I'd suggest that you change your code from this:
self.addEventListener('fetch', function(evt) {
console.log('The service worker is serving the asset.');
evt.respondWith(fromCache(evt.request));
});
对于这样的事情:
addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
if (response) {
return response; // if valid response is found in cache return it
} else {
return fetch(event.request) //fetch from internet
.then(function(res) {
return caches.open(CACHE_DYNAMIC_NAME)
.then(function(cache) {
cache.put(event.request.url, res.clone()); //save the response for future
return res; // return the fetched data
})
})
.catch(function(err) { // fallback mechanism
return caches.open(CACHE_CONTAINING_ERROR_MESSAGES)
.then(function(cache) {
return cache.match('/offline.html');
});
});
}
})
);
});
注意:有很多缓存策略,我在这里展示的是离线优先方法.有关更多信息,请此&这是必读内容.
NOTE: There are many strategies for caching, what I've shown here is offline first approach. For more info this & this is a must read.
这篇关于渐进式Web应用程序未捕获(已承诺)TypeError:无法获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!