ServiceWorker 向 FetchEvent.respondWith() 传递了一个承诺,该承诺以非响应值“未定义”解决。浏览器同步

Jon*_*rez 5 javascript node.js socket.io service-worker browser-sync

有时当我运行我的服务器时,控制台会给我一个错误:

无法加载“ http://localhost:3000/browser-sync/socket.io/?EIO=3&transport=polling&t=Lm2wn4p ”。ServiceWorker 向 FetchEvent.respondWith() 传递了一个承诺,该承诺以非响应值“未定义”解决。

我不知道发生了什么

服务工作者.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;
    })
}
Run Code Online (Sandbox Code Playgroud)

任何想法或解决方案?

小智 6

这只是一个缺少的return关键字:)

当在缓存中找到请求时,您返回响应,太棒了!但是当没有缓存时,你没有 return 语句,它最终会从你的requestBackend函数返回一个正确的响应,这会导致问题。

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

速记:

caches.match(event.request).then(function(res){
  return res || requestBackend(event);
})
Run Code Online (Sandbox Code Playgroud)