Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service Worker - Uncaught (in promise) TypeError: Failed to fetch

I have made a web app and have used service worker in my app. It's all working fine when online. The files are all cached when we run the app for the first time. But I get this error when it goes offline.

Uncaught (in promise) TypeError: Failed to fetch

I don't know why this error is occurring!

I have used pwabuilder.com for adding service worker and manifest to the web app.

This is the pwabuilder-sw.js file:

self.addEventListener('install', function(event) {
event.waitUntil(preLoad());
});

var preLoad = function() {
console.log('[PWA Builder] Install Event processing');
return caches.open('pwabuilder-offline').then(function(cache) {
    console.log('[PWA Builder] Cached index and offline page during 
Install');
    return cache.addAll([
        '/manup.js',
        'pwabuilder-sw-register.js',
        'pwabuilder-sw.js',
        'manifest.json',
        '/js/angular.min.js',
        '/js/script.js',
        '/js/materialize.min.js',
        '/css/materialize.min.css',
        '/css/style.css',
        '/offline.html',
        '/index.html'
    ]);
});
}

self.addEventListener('fetch', function(event) {
console.log('The service worker is serving the asset.');
event.respondWith(checkResponse(event.request).catch(function() {
    return returnFromCache(event.request)
}));
event.waitUntil(addToCache(event.request));
});

var checkResponse = function(request) {
return new Promise(function(fulfill, reject) {
    fetch(request).then(function(response) {
        if (response.status !== 404) {
            fulfill(response)
        } else {
            reject()
        }
    }, reject)
});
};

var addToCache = function(request) {
return caches.open('pwabuilder-offline').then(function(cache) {
    return fetch(request).then(function(response) {
        console.log('[PWA Builder] add page to offline' + response.url)
        return cache.put(request, response);
    });
});
};

var returnFromCache = function(request) {
return caches.open('pwabuilder-offline').then(function(cache) {
    return cache.match(request).then(function(matching) {
        if (!matching || matching.status == 404) {
            return cache.match('offline.html')
        } else {
            return matching
        }
    });
});
}; 

This is the pwabuilder-sw-register.js file:

if (navigator.serviceWorker.controller) {
  console.log('[PWA Builder] active service worker found, no need to register')
} else {
  //Register the ServiceWorker
  navigator.serviceWorker.register('pwabuilder-sw.js', {
    scope: './'
  }).then(function (reg) {
    console.log('Service worker has been registered for scope:' +
      reg.scope);
  });
}

Any clues?!

like image 980
Litson Thomas Avatar asked Jun 19 '17 10:06

Litson Thomas


People also ask

How do I fix Uncaught in promise TypeError Failed to fetch?

To solve the "TypeError: Failed to fetch", make sure to pass the correct configuration to the fetch method, including the URL, HTTP method and headers, and verify that the server you're making a request to is setting the correct CORS headers with the response.

What is TypeError Failed to fetch?

When you see an error saying "Failed to fetch" or get an ICE error this means that there is a connectivity issue between you and Lookback. Typically this is related to a firewall blocking your connection in some way.

How do I fix TypeError failed to fetch?

To solve the "TypeError: Failed to fetch", make sure to pass the correct configuration to the fetch method, including the URL, HTTP method and headers, and verify that the server you're making a request to is setting the correct CORS headers with the response.

Why do I get an error in fetch()?

An incorrect or incomplete URL has been passed to the fetch () method. The server you are making a request to does not send back the correct CORS headers. A wrong protocol is specified in the url. A wrong method or headers have been passed to the fetch () method. Here's an example of how the error occurs.

Why does the service worker fail when a URL fails?

My guess is that you have a URL that fails to cache and so the entire caching operation fails as well as the cache is atomic meaning: If a single URL fails the entire cache fail. Exactly. The error that op is seeing on the logs does not break the Service Worker, it is just a log.

Why did I get two cors errors when trying to fetch?

The url we passed to the fetch () method is incorrect, so we got back two errors: CORS - "No 'Access-Control-Allow-Origin' header is present on the requested resource." Make sure that the URL you're passing to the fetch method is correct and complete. You have to:


Video Answer


2 Answers

I got the same error has I was trying to cache an entire directory instead of a single file. My guess is that you have a URL that fails to cache and so the entire caching operation fails as well as the cache is atomic meaning: If a single URL fails the entire cache fail.

like image 104
Eddy Ntambwe Avatar answered Sep 21 '22 10:09

Eddy Ntambwe


I found a scenario that this error occurs.

Certain ad block extension blocks the google analytics js file, it would cause the service worker break when fetching.

Disabling the ad block extension could prevent this.

like image 42
Leslie Wong Avatar answered Sep 22 '22 10:09

Leslie Wong