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

2024-09-27 00:14:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在我的项目中实现django progressive web app,但我在缓存页面方面遇到了一些问题

在chrome中,我得到以下错误

Uncaught (in promise) TypeError: Request failed

下面是相应的代码

serviceworker.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')

...

url.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

任何帮助都将不胜感激


Tags: djangoselfeventwebappbasereturnrequest
1条回答
网友
1楼 · 发布于 2024-09-27 00:14:54

解决方案:

我在this线程上使用了一个解决方案,效果非常好。希望对某人有所帮助:)

serviceworker.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 }));
};

相关问题 更多 >

    热门问题