错误为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 }))
);
});
答案 0 :(得分:0)
如果没有真正明确预期的行为,我必须假设提问者想要处理404错误而不抛出异常。
一个选项是这个(披露:它由我编写),一个交钥匙服务工作者,它只具有缓存,网络优先,缓存优先和仅网络策略,并且不会在404上抛出错误:http://jsfiddle.net/yjcL5/104/