gpt4 book ai didi

javascript - ServiceWorker 向 FetchEvent.respondWith() 传递了一个 promise ,该 promise 以非响应值 ‘undefined’ 解析。浏览器同步

转载 作者:搜寻专家 更新时间:2023-10-31 23:45:47 24 4
gpt4 key购买 nike

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

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’.

我不知道发生了什么,

服务 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;
})
}

有什么想法或解决方案吗?

最佳答案

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

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

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

速记:

caches.match(event.request).then(function(res){
return res || requestBackend(event);
})

关于javascript - ServiceWorker 向 FetchEvent.respondWith() 传递了一个 promise ,该 promise 以非响应值 ‘undefined’ 解析。浏览器同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43956230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com