我有一个SPA应用程序,并尝试使用服务工作者来实现对PWA的支持。我缓存了一个offline.html
要在任何网络错误上显示的文件。当我的REST API调用由于没有互联网而失败时,我无法使其按需运行。
每当API调用失败时,我都想返回一个自定义Response
对象,例如状态码599,简短的状态文本以及缓存的offline.html文件的全部内容。
var CACHE_NAME = 'hypo-cache-v1';
var urlsToCache = [
'home/offline.html',
'manifest.json',
'favicon.ico'
];
self.addEventListener('install', function(event) {
self.skipWaiting();
// Perform install steps
event.waitUntil(
caches.open(CACHE_NAME).then(function(cache) {
console.log('Opened cache');
try {
return cache.addAll(urlsToCache);
} catch (error) {
console.error(error);
}
})
);
});
self.addEventListener('fetch', function(event) {
// if (event.request.mode !== 'navigate' && event.request.mode !== 'cors') {
// if (event.request.mode !== 'navigate') {
if (event.request.mode === 'no-cors') {
// Not a page navigation, bail.
return;
}
console.log('[ServiceWorker] Fetch', event.request.url, event.request.mode);
event.respondWith(
fetch(event.request)
.then(function(response) {
return response;
})
.catch(function(error) {
console.error("poa: catch", event.request.url, error, event);
if (event.request.url.indexOf("/api/") !== -1) {
var customResponse = null;
caches.match('home/offline.html').then(function(response) {
if (response) {
response.text().then(function(responseContent) {
var fallbackResponse = {
error: {
message: NETWORK_ERROR_TEXT,
networkError: true,
errorPage: responseContent
}
};
var blob = new Blob([JSON.stringify(fallbackResponse)], {type : 'application/json'});
customResponse = new Response(blob, {"status" : 599, "statusText": NETWORK_ERROR_TEXT, "headers" : {"Content-Type" : "application/json"}});
// var customResponse = new Response(NETWORK_ERROR_TEXT, {"status" : 599, "statusText": NETWORK_ERROR_TEXT, "headers" : {"Content-Type" : "text/plain"}});
console.log("poa: returning custom response", event.request.url, customResponse, fallbackResponse);
return customResponse;
});
}
});
console.log("poa: how to avoid getting here???", event.request.url, customResponse);
// var fallbackResponse = {
// error: {
// message: NETWORK_ERROR_TEXT,
// networkError: true
// }
// };
// var blob = new Blob([JSON.stringify(fallbackResponse)], {type : 'application/json'});
// var customResponse = new Response(blob, {"status" : 599, "statusText": NETWORK_ERROR_TEXT, "headers" : {"Content-Type" : "application/json"}});
// console.log("poa: returning custom response", event.request.url, customResponse);
// return customResponse;
} else {
return caches.match('home/offline.html');
}
})
);
});
我必须在诺言中遗漏一些基本内容,但无法弄清楚。我想返回customResponse
的caches.match()
承诺,而是将customResponse
返回,但只有后console.log("poa: how to avoid getting here???");
,这使得发起Ajax调用收到状态0和状态文本“错误”的响应。我想得到我的自定义回复...
这是调用代码的代码:
$.ajax({
url: url,
dataType: "json",
contentType: "application/json; charset=utf-8",
cache: false,
headers: {
"Authorization": "Bearer " + token
},
'timeout': timeout,
beforeSend: function(jqXhr, options) {
this.url += "-" + userId;
logUrl = this.url;
}
}).done(function(data) {
done(null, data);
}).fail(function(data, textStatus, errorThrown) {
var end = Date.now();
var diff = end - start;
console.error("Error fetching from resource: ", diff, timeout, data, textStatus, errorThrown, new Error().stack);
...
...
我应该如何重写自己的代码fetch
,catch
以便可以将我的customResponse返回给调用者?
我自己发现了错误...我忘了return
在Promise链中添加一些错误。
对于任何可能感兴趣的人,以下是有效的更新代码:
event.respondWith(
fetch(event.request)
.then(function(response) {
return response;
})
.catch(function(error) {
console.error("poa: catch", event.request.url, error, event);
if (event.request.url.indexOf("/api/") !== -1) {
var customResponse = null;
return caches.match('home/offline.html').then(function(response) {
if (response) {
return response.text().then(function(responseContent) {
var fallbackResponse = {
error: {
message: NETWORK_ERROR_TEXT,
networkError: true,
errorPage: responseContent
}
};
var blob = new Blob([JSON.stringify(fallbackResponse)], {type : 'application/json'});
customResponse = new Response(blob, {"status" : 599, "statusText": NETWORK_ERROR_TEXT, "headers" : {"Content-Type" : "application/json"}});
// var customResponse = new Response(NETWORK_ERROR_TEXT, {"status" : 599, "statusText": NETWORK_ERROR_TEXT, "headers" : {"Content-Type" : "text/plain"}});
console.log("poa: returning custom response", event.request.url, customResponse, fallbackResponse);
return customResponse;
});
}
});
...
...
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句