Django 服务工作者无法缓存页面:未捕获(在承诺中)类型错误:请求失败



我正在尝试在我的项目中实现django-progressive-web-app,并且在缓存页面时遇到了一些问题。

在铬中,我收到以下错误

Uncaught (in promise) TypeError: Request failed

这是相应的代码

服务工作者.js

var staticCacheName = 'djangopwa-v1';
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(staticCacheName).then(function(cache) {
return cache.addAll([
'/base_layout'
]);
})
);
});
self.addEventListener('fetch', function(event) {
var requestUrl = new URL(event.request.url);
if (requestUrl.origin === location.origin) {
if ((requestUrl.pathname === '/')) {
event.respondWith(caches.match('/base_layout'));
return;
}
}
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});

views.py

...
def base_layout(request):
return render(request, 'main/home.html')
...

urls.py

urlpatterns = [
...
#pwa
path('', include('pwa.urls')),
]

我遵循了本教程:https://medium.com/beginners-guide-to-mobile-web-development/convert-django-website-to-a-progressive-web-app-3536bc4f2862

任何帮助将不胜感激!!

解决方案:

我在这个线程上使用了一个解决方案,它就像一个魅力。希望它对某人有所帮助:(

服务工作者.js

var staticCacheName = 'djangopwa-v1';
self.oninstall = function (evt) {
evt.waitUntil(caches.open(staticCacheName).then(function (cache) {
return Promise.all(['/', 'main/home.html'].map(function (url) {
return fetch(new Request(url, { redirect: 'manual' })).then(function (res) {
return cache.put(url, res);
});
}));
}));
};
self.onfetch = function (evt) {
var url = new URL(evt.request.url);
if (url.pathname != '/' && url.pathname != 'main/home.html') return;
evt.respondWith(caches.match(evt.request, { cacheName: staticCacheName }));
};

最新更新