服务工作者可以缓存POST请求吗?

时间:2016-02-08 13:20:38

标签: javascript post request service-worker pwa

我尝试在fetch事件中缓存服务工作者的POST请求。

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

当我尝试使用相同的POST API时,caches.match(event.request)给了我未定义的内容。

但是当我为GET方法做同样的事情时,它起作用了:caches.match(event.request) GET请求给了我一个回应。

服务工作者可以缓存POST请求吗? 如果他们不能,我们可以使用什么方法让应用真正脱机?

5 个答案:

答案 0 :(得分:21)

您无法使用Cache 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。

答案 1 :(得分:3)

在最近的带有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。随时使用它!

答案 2 :(得分:1)

如果您要谈论表单数据,则可以拦截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... )
      }
})

答案 3 :(得分:0)

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

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

遵循此解决方案要考虑的另一方面是,如果多个用户具有同时同步的脱机更改,则不能保证更改将在服务器上按正确的时间顺序执行,因为Firestore使用< em>先到先得逻辑。

答案 4 :(得分:0)

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

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