Service Worker如何处理302重定向响应?
Hey there, I’ve run into this exact issue before—super frustrating when everything else with your Service Worker works smoothly, but redirects throw that cryptic error! Let’s break down what’s happening and fix it step by step.
Why This Error Happens
The error message spells out the core problem: your Service Worker is returning a raw 302 redirected response for a request that doesn’t allow unhandled redirects by default. Browsers expect fetch requests to either follow redirects automatically or handle them explicitly, and when your Service Worker serves up a 302 without accounting for this, it breaks the loading flow.
Step-by-Step Solutions
1. Update Your Fetch Event to Handle Redirects Explicitly
In your Service Worker’s fetch listener, you need to either let the browser follow redirects automatically or manually resolve the redirect to return the final resource. Here’s how to adjust your code:
self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then((cachedResponse) => { // Check if we have a cached response if (cachedResponse) { // Identify redirect status codes const isRedirect = [301, 302, 303, 307, 308].includes(cachedResponse.status); if (isRedirect) { // Fetch the final resource the redirect points to return fetch(cachedResponse.url, { redirect: 'follow' }); } return cachedResponse; } // For network requests, explicitly allow following redirects return fetch(event.request, { redirect: 'follow' }).then((networkResponse) => { // Only cache the final resource, not the temporary redirect if (![301, 302, 303, 307, 308].includes(networkResponse.status)) { caches.open('your-cache-name').then((cache) => { cache.put(event.request, networkResponse.clone()); }); } return networkResponse; }); }) ); });
2. Stop Caching Redirect Responses
302 redirects are temporary by nature, so caching them is usually a bad practice. The code above skips storing any redirect responses in your cache, ensuring your Service Worker only serves up the actual content users need—no stale or invalid redirects later.
3. Double-Check Request Redirect Mode
Make sure any custom fetch requests in your main app aren’t setting redirect: 'manual' or redirect: 'error' unless you intentionally want to handle redirects yourself. Sticking with the default redirect: 'follow' will play nicely with your Service Worker’s logic.
Quick Testing Checklist
After updating your Service Worker, don’t forget to:
- Unregister the old Service Worker in your browser’s dev tools (Application > Service Workers)
- Clear your cache to remove any leftover redirect responses
- Reload the page to activate the updated Service Worker
That should squash the error and let your redirected pages load as expected!
内容的提问来源于stack exchange,提问作者Loann.M

