问题描述
我使用 ReactJS 构建了一个渐进式 Web 应用程序,但遇到了问题.我正在使用 mockApi 来获取数据.离线时,我的应用程序不起作用,因为 Service Worker 仅缓存静态资产.
I built a Progressive Web App with ReactJS and have an issue. I am using mockApi to fetch the data.When offline, my app doesn't work since the service worker only caches static assets.
如何将来自 mockApi 的 HTTP GET 调用保存到缓存存储中?
How can I save HTTP GET calls from mockApi into the cache storage?
推荐答案
除了静态资源,您还可以定义要缓存的 URL:
Along with your static assets, you can define which URLs do you want to cache:
var CACHE_NAME = 'my-cache_name';
var targetsToCache = [
'/styles/myStyles.scss',
'www.stackoverflow.com/'
];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
return cache.addAll(targetsToCache);
})
);
});
然后你必须指示你的 service worker 拦截网络请求,看看是否与 targetsToCache
中的地址匹配:
Then you have to instruct your service worker to intercept the network requests and see if there is a match with the addresses in the targetsToCache
:
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
// This returns the previously cached response
// or fetch a new once if not already in the cache
return response || fetch(event.request);
})
);
});
我写了一个系列如果您有兴趣了解更多有关渐进式 Web 应用的文章.
这篇关于如何在 React PWA 中将数据从 API 缓存到缓存存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!