Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A ServiceWorker passed a promise to FetchEvent.respondWith() that resolved with non-Response value ‘undefined’. Browser-sync

sometimes when i run my server the console gives me an error:

Failed to load ‘http://localhost:3000/browser-sync/socket.io/?EIO=3&transport=polling&t=Lm2wn4p’. A ServiceWorker passed a promise to FetchEvent.respondWith() that resolved with non-Response value ‘undefined’.

and i don't know what happend,

Service-worker.js :

importScripts('assets/js/cache-polyfill.js');

var CACHE_VERSION = 'app-v1';
var CACHE_FILES = [
    'index.html'
];

self.addEventListener('install', function (event) {
    event.waitUntil(
        caches.open(CACHE_VERSION)
            .then(function (cache) {
                console.log('Opened cache');
                return cache.addAll(CACHE_FILES);
            })
    );
});

self.addEventListener('activate', function (event) {
    event.waitUntil(
        caches.keys().then(function(keys){
            return Promise.all(keys.map(function(key, i){
                if(key !== CACHE_VERSION){
                    return caches.delete(keys[i]);
                }
            }))
        })
    )
});

self.addEventListener('fetch', function (event) {
    event.respondWith(
        caches.match(event.request).then(function(res){
            if(res){
                return res;
            }
            requestBackend(event);
        })
    )
});

function requestBackend(event){
    var url = event.request.clone();
    return fetch(url).then(function(res){
        //if not a valid response send the error
        if(!res || res.status !== 200 || res.type !== 'basic'){
            return res;
        }

        var response = res.clone();

        caches.open(CACHE_VERSION).then(function(cache){
            cache.put(event.request, response);
        });

        return res;
    })
}

any idea or solution?

like image 546
Jonathan Perez Avatar asked May 13 '17 17:05

Jonathan Perez


1 Answers

It's just a missing return keyword :)

When the request is found in cache your returning the response, great! but when not cached you don't have return statement which will eventually return a correct response from your requestBackend function and that's causing the issue.

self.addEventListener('fetch', function (event) {
    event.respondWith(
        caches.match(event.request).then(function(res){
            if(res){
                return res;
            }
            return requestBackend(event);
        })
    )
});

shorthand:

caches.match(event.request).then(function(res){
  return res || requestBackend(event);
})
like image 174
Zouhir Avatar answered Sep 18 '22 01:09

Zouhir