Service Worker 可以缓存 POST 个请求吗?

Can service workers cache POST requests?

我试图在获取事件时在 service worker 中缓存 POST 请求。

我用了cache.put(event.request, response),但是返回的promise被TypeError: Invalid request method POST.拒绝了。

当我试图点击相同的 POST API 时,caches.match(event.request) 给出了未定义的结果。

但是当我对 GET 方法执行相同操作时,它起作用了:caches.match(event.request) GET 请求给了我一个响应。

Service Worker 可以缓存 POST 请求吗? 如果他们做不到,我们可以使用什么方法让应用程序真正离线?

您无法使用缓存 API 来缓存 POST 请求。参见 https://w3c.github.io/ServiceWorker/#cache-put(第 4 点)。

规范存储库中有相关讨论:https://github.com/slightlyoff/ServiceWorker/issues/693

ServiceWorker Cookbook 中提供了一个有趣的解决方案:https://serviceworke.rs/request-deferrer.html 基本上,该解决方案将请求序列化到 IndexedDB。

如果你说的是表单数据,那么你可以拦截fetch事件,按照下面类似的方式读取表单数据,然后将数据保存到indexedDB中。

//service-worker.js
self.addEventListener('fetch', function(event) {
      if(event.request.method === "POST"){
         var newObj = {};

               event.request.formData().then(formData => {

                for(var pair of formData.entries()) {
                  var key = pair[0];
                  var value =  pair[1];
                  newObj[key] = value;
                }

              }).then( ...save object in indexedDB... )
      }
})

我在最近的一个带有 GraphQL 的项目中使用了以下解决方案 API:我使用请求的序列化表示作为缓存,将来自 API 路由的所有响应缓存在 IndexedDB 对象存储中钥匙。然后如果网络不可用,我使用缓存作为后备:

// ServiceWorker.js
self.addEventListener('fetch', function(event) {
    // We will cache all POST requests to matching URLs
    if(event.request.method === "POST" || event.request.url.href.match(/*...*/)){
        event.respondWith(
            // First try to fetch the request from the server
        fetch(event.request.clone())
            // If it works, put the response into IndexedDB
            .then(function(response) {
                // Compute a unique key for the POST request
                var key = getPostId(request);
                // Create a cache entry
                var entry = {
                    key: key,
                    response: serializeResponse(response),
                    timestamp: Date.now()
                };

                /* ... save entry to IndexedDB ... */

                // Return the (fresh) response
                return response;
            })
            .catch(function() {
                // If it does not work, return the cached response. If the cache does not
                // contain a response for our request, it will give us a 503-response
                var key = getPostId(request);
                var cachedResponse = /* query IndexedDB using the key */;
                return response;
            })
        );
    }
})

function getPostId(request) {
    /* ... compute a unique key for the request incl. it's body: e.g. serialize it to a string */
}

这是我使用 Dexie.js 作为 IndexedDB 包装器的特定解决方案的 full code。放心使用吧!

另一种提供完全离线体验的方法可以通过使用Cloud Firestore offline persistence获得。

POST / PUT 请求在本地缓存数据库上执行,然后在用户恢复其 Internet 连接后立即自动同步到服务器(请注意,有 500 个离线请求的限制)。

遵循此解决方案需要考虑的另一个方面是,如果多个用户同时进行同步的离线更改,则无法保证这些更改将按照 Firestore 使用的服务器上的正确时间顺序执行先到先得逻辑。

根据https://w3c.github.io/ServiceWorker/#cache-put(第 4 点)。

        if(request.method !== "GET") {
            return Promise.reject('no-match')
        }