16
votes

I installed a service worker on my application, it gets installed well, activated well, and the caching is ok too.

But when the caching is done when I click on a page that is a 302, it tells me:

The FetchEvent for "http://localhost:8000/form/" resulted in a network error response: a redirected response was used for a request whose redirect mode is not "follow".

I've been reading a lot on the subject, I've consulted the posts here : Service Worker breaking 301 redirects, and there https://github.com/w3c/ServiceWorker/issues/737 and there https://github.com/GoogleChromeLabs/sw-precache/issues/220

As I understand the default redirect mode when fetching is {redirect: "follow"}, but when I catch the redirect mode from my redirected page I can see it is {redirect: "manual"} So basically I would have to do something when it is "manual".

Thought I'm a bit confused and I'm struggling on how to implement this in my code.

Here's my code:

const STATIC_CACHE_NAME = 'exell-static-v28';
const DYNAMIC_CACHE_NAME = 'exell-dynamic-v4';

// INSTALLING THE SERVICE WORKER AND PRECACHING APPSHELL
self.addEventListener('install', function(event) {
  console.log('[Service Worker] Service Worker installed');
  event.waitUntil(
    caches.open(STATIC_CACHE_NAME) // Create a static cache
    .then(function(cache) {
      console.log('[Service Worker] Precaching App Shell');
      cache.addAll([   // Add static files to the cache
        '/',
        '/build/app.js',
        '/build/global.css',
        'login',
        'logout',
        'offline',
        'form/',
        'form/new/first_page',
        'form/new/second_page',
        'form/new/third_page',
        'form/new/fourth_page',
        'form/new/fifth_page',
        'form/new/sixth_page',
        'profile/',
        'build/fonts/BrandonGrotesque-Medium.a989c5b7.otf',
        'build/fonts/BrandonText-Regular.cc4e72bd.otf',
      ]);
    })
  );
});

// ACTIVATING THE SERVICE WORKER
self.addEventListener('activate', function(event) {
  console.log('[Service Worker] Service Worker activated');
  event.waitUntil(
    caches.keys()
    .then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (key !== STATIC_CACHE_NAME && key !== DYNAMIC_CACHE_NAME) { // If old cache exists
          console.log('[Service Worker] Deleting old cache', key);
          return caches.delete(key);  // Delete it and replace by new one
        }
      }));
    })
  );
  return self.clients.claim();
});


// FETCHING
self.addEventListener('fetch', function(event) {

  // Do not waste time with files we don't want to cache
  if (event.request.url.match(/ajax.js/)) {
    return;
  }

  event.respondWith(
    caches.match(event.request) // Retrieve data from the cache
     .then(function(response) {
        if (response) {
          return response;  // If there is a response, return it
        } else {
          return fetch(event.request) // Otherwise fetch from network
            .then(function(res) {
              return caches.open(DYNAMIC_CACHE_NAME)
                .then(function(cache) {
                  cache.put(event.request.url, res.clone()); // Store the response in the dynamic cache
                  return res; // And return the response
                });
            })
            .catch(function() {  // If no network
              return caches.open(STATIC_CACHE_NAME) // Open the static cache
               .then(function(cache) {
                 cache.match('offline'); // Look for the offline default template and return it
               });
            });
         }
      })
    );
});
2
Did you solve this?tony
Thanks. I already saw that post. No I didn't solve it unfortunately, it got me crazy for weeks, and then I changed project.Loann.M

2 Answers

11
votes

Any 30x responses are expected to have a type property that resolves to "opaqueredirect", which you could check for, and react to appropriately. Maybe you would want to check this link: Response.type

opaqueredirect: The fetch request was made with redirect: "manual".
The Response's status is 0, headers are empty, body is null and trailer is empty.

Therefore to solve your issue, you should check for:

response.type === 'opaqueredirect'

instead of any checks relating to response.status, for example similar to
(the checks bellow will not work as response.status will be 0)

response.status === 301 || response.status === 302

Cheers, and happy coding!

-1
votes

Possible solution

For the pages that can possibly throw a 3xx ... simply don’t cache stuff. https://medium.com/@boopathi/service-workers-gotchas-44bec65eab3f

self.addEventListener('fetch', event => {

    // path throw a 3xx - don’t cache
    if(event.request.url == '{{url}}' ) {
        return;
    }

    ...

}