错误是Uncaught (in promise) Error: Not Found.
这似乎是由于窗口在自我内部不可用。自我既是服务人员又是窗口。新错误() - 未捕获(承诺)错误:未找到
下面的代码是在index.html中,一切工作正常。当网络请求返回404时,它将评估throwOnError
并显示此错误。
var throwOnError = (response) => {
if (response.status >= 200 && response.status < 300 || response.status === 0) {
return response;
}
throw new Error(response.statusText);
};
function cacheableRequestFailingToCacheStrategy({ event, cache }) {
return fetch(event.request)
.then(throwOnError) // do not cache errors
.then(response => {
cache.put(event.request, response.clone());
return response;
})
.catch(() => cache.match(event.request));
}
function isRequestForStatic(request) {
return /.(png|jpg|jpeg|gif|css|js)$/.test(request.url);
}
function isSideEffectRequest(request) {
console.log(request.method);
return ["POST", "PUT", "DELETE"].includes(request.method);
}
function cacheFailingToCacheableRequestStrategy({ event, cache }) {
return cache.match(event.request)
.then(throwOnError)
.catch(() => fetch(event.request)
.then(throwOnError)
.then(response => {
cache.put(event.request, response.clone());
return response;
})
);
}
function requestFailingWithNotFoundStrategy({ event }) {
return fetch(event.request)
.catch(() => {
const body = JSON.stringify({ error: "Sorry, you are offline. Please, try later." });
const headers = { "Content-Type": "application/json" };
const response = new Response(body, { status: 404, statusText: "Not Found", headers });
return response;
});
}
self.addEventListener("fetch", event => {
console.log(event.request);
if (isSideEffectRequest(event.request)) {
console.log("post", event.request.method);
event.respondWith(requestFailingWithNotFoundStrategy({ event }));
return;
}
if (isRequestForStatic(event.request)) {
event.respondWith(
caches.open(CACHE_NAME)
.then(cache => cacheFailingToCacheableRequestStrategy({ event, cache }))
);
return;
}
event.respondWith(
caches.open(CACHE_NAME)
.then(cache => cacheableRequestFailingToCacheStrategy({ event, cache }))
);
});
代码在我看来像是服务工作者,但你说“下面的代码在index.html中”。你能澄清吗? –
另外:因为你有代码实际上产生“未找到”,并抛出'错误'对象,你实际上试图解决什么问题? –
首先 - 这是服务人员...但我没有把它保存在单独的sw.js文件中。它在index.html中是全局服务工作者的范围。 –