【发布时间】:2020-06-17 11:30:03
【问题描述】:
我的服务工作者中有这个获取功能,当 pwa 离线时,我尝试使用不同的图像进行响应。 catch 里面的 fetch 函数抛出:Uncaught (in promise) TypeError: Failed to fetch。
self.addEventListener('fetch', (e) => {
if (e.request.method === 'GET') {
e.respondWith(
caches.match(e.request).then((cachedResponse) => {
return cachedResponse || fetch(e.request.url)
.then((res) => {
return res;
}).catch(() => {
//if it is a image then
let url1 = e.request.url.replace(".jpg", "_mini.jpg");
return fetch(url1);
/* Or like this
caches.match(url1).then((cResp) => {
return cResp;
})
*/
})
})
)
}
});
当您离线并以“迷你”替代图像响应时是否无法捕获错误,或者我做错了什么?
【问题讨论】:
-
请定义“它不起作用”。它会出错吗?产生不正确的图像?显示空白页?使程序崩溃而没有错误?导致页面无限加载? “它不起作用”是诊断此代码中问题的最少量有用细节
-
fetch(url1) 失败:未捕获(承诺中)类型错误:无法获取。但就像@Guerric P 所说,这是因为 fetch 不能离线工作。
标签: javascript fetch service-worker progressive-web-apps