1

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

我一定错过了一些基本的承诺,但无法弄清楚。我想customResponsecaches.match()promisecustomResponse中返回 ,而是在 之后才返回console.log("poa: how to avoid getting here???");,这使得发起的 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以便我可以将我的 customResponse 返回给调用者?

4

1 回答 1

1

我自己发现了错误......我忘了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;
                            });
                        }
                    });
...
...
...
于 2019-08-06T10:52:27.907 回答