当与服务器没有连接时,从缓存返回响应

Returning response from cache when there is no connection to server

本文关键字:缓存 返回 响应 连接 服务器      更新时间:2023-09-26

在service worker的帮助下,如果没有连接到服务器,我想从缓存返回响应。然后,如果缓存中没有正确的响应,我希望返回自定义响应。

现在,我有这样的代码:

this.addEventListener('fetch', function (event) {
    event.respondWith(
        timeout(5000, fetch(event.request)).catch(function() {
            return caches.match(event.request);
        })
    );
});

我想有这样的东西:

this.addEventListener('fetch', function (event) {
    event.respondWith(
        timeout(5000, fetch(event.request)).catch(function() {
            caches.match(event.request).then(function(cacheResponse) {
                return cacheResponse;
            }).catch(function () {
                return new Response('No cache found');
            })
        })
    );
});

或者更好的是

this.addEventListener('fetch', function (event) {
    event.respondWith(
        timeout(5000, fetch(event.request)).catch(function() {
            caches.match(event.request).then(function(cacheResponse) {
                return cacheResponse;
            }).catch(function () {
                return caches.match(offlineMessageUrl);
            })
        })
    );
});

从缓存的文档中。匹配函数,承诺总是被解决。使用Response对象解析,如果没有找到匹配,则使用undefined解析。你可以试试这个:-

    this.addEventListener('fetch', function (event) {
        event.respondWith(
            caches.match(event.request).then(function(cacheResponse) {
                return cacheResponse || new Response('No cache found');
            }).catch(function () {
                return new Response('No cache found');
            })
        );
    });