1
votes

I've been trying to build a progressive Django Web App with a service worker and django-pwa. Everything seems to work fine, but whenever I load the page, turn on offline mode in Chrome, and reload, I get this error:

"The FetchEvent for "https://haverford.getdibs.app/login/?redirect_to=/dashboard/" resulted in a network error response: a redirected response was used for a request whose redirect mode is not "follow"".

Now I've seen that someone else came into a seemingly similar problem here, but I don't quite understand what's going on in the answer. I think I need to set the redirect mode to "follow" for a request that I make with my fetch, but I'm not sure how to do that.

Here is my service worker:

   var staticCacheName = "django-pwa-v" + new Date().getTime();
var filesToCache = [
  '/offline',
];

// Cache on install
self.addEventListener("install", event => {
    this.skipWaiting();
    event.waitUntil(
        caches.open(staticCacheName)
            .then(cache => {
                return cache.addAll(filesToCache);
            })
    )
});

// Clear cache on activate
self.addEventListener('activate', event => {
    event.waitUntil(
        caches.keys().then(cacheNames => {
            return Promise.all(
                cacheNames
                    .filter(cacheName => (cacheName.startsWith("django-pwa-")))
                    .filter(cacheName => (cacheName !== staticCacheName))
                    .map(cacheName => caches.delete(cacheName))
            );
        })
    );
});


// Serve from Cache
self.addEventListener("fetch", event => {
    event.respondWith(
        caches.match(event.request)
            .then(response => {
                return response || fetch(event.request);
            })
            .catch(() => {
                return caches.match('offline');
            })
    )
});

I'm under the impression that i somehow have to make the event.request's redirect mode to 'follow', but when I put a breakpoint in that line and examine the event.request object, its redirect is set to 'manual'. How would I change it?

Any help in my quest to understanding what the issue actually is would be much appreciated.

Thank you.

1

1 Answers

3
votes

Thanks a lot, sideshowbarker.

Method 1 in this link helped solve my problem.

I replaced my install event from this:

self.addEventListener("install", event => {
 this.skipWaiting();
 event.waitUntil(
     caches.open(staticCacheName)
         .then(cache => {
             return cache.addAll(filesToCache);
         })
  )
});

to this:

self.addEventListener("install", event => {
    this.skipWaiting();
    event.waitUntil(
        caches.open(staticCacheName)
            .then(cache => {
        return fetch('/offline')
        .then(response => cache.put('/offline', new Response(response.body)));
            })
    )
});

Of course, right now it only works for that one URL endpoint ('/offline'), but it would be similar for multiple fetch requests I suppose.