![](/img/trans.png)
[英]Service Worker - Uncaught (in promise) TypeError: Failed to fetch
[英]how to solve service_worker_en.js:3 Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'WorkerGlobalScope'?
我的 Chrome 控制台在我的網站上出現此錯誤
service_worker_en.js:3 Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'WorkerGlobalScope': Cannot construct a Request with a Request object that has already been used.
我已經閱讀了這篇關於 SO的文章,但仍然無法弄清楚我的代碼到底出了什么問題。 這是我的服務人員代碼
self.addEventListener("install", function(event) {
event.waitUntil(preLoad());
});
var preLoad = function() {
console.log("Installing web app");
return caches.open("offline").then(function(cache) {
console.log("caching index and important routes");
return cache.addAll(["/", "/devotional-language-en-tab-9"]);
});
};
self.addEventListener("fetch", function(event) {
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("offline").then(function(cache) {
return fetch(request).then(function(response) {
console.log(response.url + " was cached");
return cache.put(request, response);
});
});
};
var returnFromCache = function(request) {
return caches.open("offline").then(function(cache) {
return cache.match(request).then(function(matching) {
if (!matching || matching.status == 404) {
return cache.match("offline_en.html");
} else {
return matching;
}
});
});
};
根據 Chrome 的說法,錯誤主要在這兩行:
如何解決 service_worker_en.js:3 Uncaught (in promise) TypeError: ? 請我需要一個具體的答案來解決這個問題。
您需要在使用API_ENDPOINT.clone()
獲取之前克隆請求 object,因為 object 已被使用。
var addToCache = function(request) {
return caches.open("offline").then(function(cache) {
return fetch(request.clone()).then(function(response) {
console.log(response.url + " was cached");
return cache.put(request, response);
});
});
};
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.