2
votes

I use this Command in fetch in Service Worker

 if (event.request.method =='POST') {

        event.respondWith(fetch(event.request,{method: 'post'}));
        return;
    }

but I get this error :

Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': Cannot construct a Request with a Request whose mode is 'navigate' and a non-empty RequestInit.

What should I do ?

1
What 's the type of event? - sp1rs

1 Answers

2
votes

Based on the sample code that you provide, it looks like you want to just implement the default, pretend-like-there's-no-service-worker behavior when you handle fetch event for a POST request.

The easiest way to do that is to simply not call event.respondWith() in the first place. Calling event.respondWith() is optional, and if you don't call it in a fetch handler, the service worker will look for any other registered fetch handlers and give them a chance to respond.

If none of the fetch event handlers respond, then the request will be fulfilled via either the browser cache (depending on the request headers and state of the cache) or the network, exactly as if there were no service worker involvement.

If, for some reason, you really need to call `event.respondWith(), but you want to mimic the default behavior, then using

event.respondWith(fetch(event.request));

should work, i.e. leave out the {method: 'post'} bit. The event.request already knows that it's a POST, so it's not necessary to pass anything else in to fetch() in order to tell it that.