【问题标题】:Django service worker not able to cache page : Uncaught (in promise) TypeError: Request failedDjango 服务人员无法缓存页面:未捕获(承诺)类型错误:请求失败
【发布时间】:2020-01-16 05:35:05
【问题描述】:

我正在尝试将 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')

...

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

任何帮助将不胜感激!!!

【问题讨论】:

    标签: python django service progressive-web-apps


    【解决方案1】:

    解决方案:

    我在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 }));
    };
    

    【讨论】:

      猜你喜欢
      • 2018-09-25
      • 1970-01-01
      • 2017-11-21
      • 2021-03-17
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      • 2020-12-01
      • 2022-09-24
      相关资源
      最近更新 更多