我怎样才能 return 我的脱机文件的内容在抓取捕获?

How can I return content of my offline file in a fetch catch?

我有一个 SPA 应用程序,正在尝试使用服务工作者实现对 PWA 的支持。我缓存了一个 offline.html 文件,我想在出现任何网络错误时显示该文件。当我的 REST API 调用由于没有互联网而失败时,我无法让它按我想要的方式工作。

每当 API 调用失败时,我想 return 自定义 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 的一些基本内容,但无法弄清楚。我想 return caches.match() 承诺中的 customResponse,但是 customResponse 是 returned 但仅在 console.log("poa: how to avoid getting here???"); 之后,这使得启动 ajax 调用收到状态为 0 和状态文本 "error" 的响应。我想得到我的自定义回复...

调用代码如下:

                $.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 以便我可以 return 我的 customResponse 给来电者?

我自己发现了错误...我忘记在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;
                            });
                        }
                    });
...
...
...