gpt4 book ai didi

javascript - 如何在 fetch catch 中返回脱机文件的内容?

转载 作者:行者123 更新时间:2023-12-02 23:10:45 25 4
gpt4 key购买 nike

我有一个 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');
}
})
);
});

我一定错过了一些基本的 promise ,但无法弄清楚。我想在 caches.match() promise 中返回 customResponse,但是 customResponse 只会在 console 之后返回.log("poa: 如何避免到达这里???");,这使得发起的ajax调用收到状态为0且statusText为“错误”的响应。我想得到我的自定义响应...

下面是调用代码:

                $.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);
...
...

我应该如何重写我的 fetchcatch 以便我可以将自定义响应返回给调用者?

最佳答案

我自己发现了错误...我忘记在promise链中添加一些return

对于任何可能感兴趣的人,这里是工作更新的代码:

    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;
});
}
});
...
...
...

关于javascript - 如何在 fetch catch 中返回脱机文件的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57373856/

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