且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-10-23 19:01:20

你可以'使用Cache API缓存POST请求。请参阅 https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#cache-put -method (第2.2点)。



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



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


I tried to cache a POST request in a service worker on fetch event.

I used cache.put(event.request, response), but the returned promise was rejected with TypeError: Invalid request method POST..

When I tried to hit the same POST API, caches.match(event.request) was giving me undefined.

But when I did the same for GET methods, it worked: caches.match(event.request) for a GET request was giving me a response.

Can service workers cache POST requests? In case they can't, what approach can we use to make apps truly offline?

You can't cache POST requests using the Cache API. See https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#cache-put-method (point 2.2).

There's a related discussion in the spec repository: https://github.com/slightlyoff/ServiceWorker/issues/693

An interesting solution is the one presented in the ServiceWorker Cookbook: https://serviceworke.rs/request-deferrer.html Basically, the solution serializes requests to IndexedDB.