Workbox POST request can't be cached.
See original GitHub issueLibrary Affected: workbox-core
Issue or Feature Request Description:
Hi @jeffposnick
I have an url which is something like this : https://api.com/data
… In my app, I use axios
to make requests in multiple places for this same url, but with different request payloads.
-
One page might create a request with the body:
example:1
and another oneexample:2
. Since the url for these two are the same, I can’t just use the route and strategy of workbox. So, should I usecacheKeyWillBeUsed
and figure out in there what the request payload’s key is to distinguish between these same urls, but different payloads ? -
I tried this:
registerRoute(
new RegExp(`${config.api.url.replace(/\./g,'\\.')}.*/metric`),
new NetworkFirst({
cacheName: config.app.cache.api,
}),
'POST'
)
but it tells me:
cacheWrapper.js:192 Uncaught (in promise) attempt-to-cache-non-get-request: Unable to cache ‘https://test.com/metric’ because it is a ‘POST’ request and only ‘GET’ requests can be cached.
Then I looked through the src code and found this:
if (process.env.NODE_ENV !== 'production') {
if (request.method && request.method !== 'GET') {
throw new WorkboxError('attempt-to-cache-non-get-request', {
url: getFriendlyURL(request.url),
method: request.method,
});
}
}
This code is located in workbox-core/src/_private/cacheWrapper.ts
.
I tried CacheFirst
strategy too, but with no luck. Also it looks like service worker intercepts POST request , but maybe, this error is due to the fact that after getting the response back, workbox can’t put it into the Cache API because Cache API doesn’t support this. Is that right and the only choice i got is to store it in indexeddb?
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
There’s nothing that Workbox can do about this, as the underlying Cache Storage API doesn’t support using a non-
GET
request as a key in a cache.If your goal is to attempt to queue up and “replay” a failed
POST
request when the browser comes back online, then theworkbox-background-sync
module can help with that. That will write failed request bodies to IndexedDB and then retry them using the Background Sync API (or at startup, on browsers that don’t support it).Alternatively, you can do whatever you’d prefer in your
handlerCallback
when you detect a network error, including write to IndexedDB if you’d rather handle the retry logic yourself.Hmm, that’s not something that’s ever come up before. Our assumption has been that if there’s a request for a URL that’s in the precache manifest that the precached response should be used, but you’re right that it really should only happen if it’s a
GET
request.@philipwalton is working on a revision of the
workbox-precaching
code for v6, and this falls into the category of something that it would make sense to fix. I’ve flagged it for him.In the meantime, hopefully this is something you can avoid doing “in the wild.”