【发布时间】:2020-04-01 16:29:33
【问题描述】:
我使用 Create-React-App 创建了一个 SPA(单页应用程序)。我向它添加了一个服务工作者,以便在没有网络连接时可以加载 SPA。 Service Worker 成功缓存了所有资源,但在没有网络连接时响应失败。我已经尝试了很多东西,但无法让它为资产提供离线功能。它给出以下错误消息:
Uncaught (in promise) TypeError: Failed to fetch
我的 service worker 注册成功,也成功缓存了资产。 Service Worker 代码:
const thingsToCache = [
'index.html',
'static/js/1.cb2fedf5.chunk.js',
'static/js/main.5e7fdc75.chunk.js',
'static/js/runtime~main.229c360f.js',
'static/css/main.ca6d346b.chunk.css',
'static/media/roboto.18d44f79.ttf',
'static/media/comfortaa.7d0400b7.ttf',
];
this.addEventListener('install', event => {
event.waitUntil(
caches.open('v1').then(cache => {
return cache.addAll(thingsToCache);
})
);
});
this.addEventListener('fetch', event => {
//respond to fetch requests here
caches
.match(event.request)
.then(cachedRes => {
if (cachedRes) {
event.respondWith(cachedRes);
} else {
throw new Error('No match found in cache!');
}
})
.catch(() => {
return fetch(event.request);
});
});
如果您需要资产,请点击以下链接:
https://github.com/Twaha-Rahman/pwa-problem-assets
感谢您的所有帮助!
【问题讨论】: