I keep getting this error in the console log
Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': Cannot construct a Request with a Request object that has already been used.
I tried changing my service worker but it doesn't work
self.addEventListener('install', (event) => event.waitUntil(preLoad()));
const preLoad = function () {
return caches.open('cc-offline').then((cache) => {
return cache.addAll(['/offline.html', '/index.html']);
});
}
self.addEventListener('fetch', (event) => {
event.respondWith(checkResponse(event.request).catch(function () {
return returnFromCache(event.request)
}));
event.waitUntil(addToCache(event.request));
});
const checkResponse = (request) => {
return new Promise((fulfill, reject) => {
fetch(request).then((response) => {
(response.status !== 404) ? fulfill(response) : reject()
}, reject)
});
};
const addToCache = (request) => {
return caches.open('cc-offline').then((cache) => {
return fetch(request).then((response) => {
return cache.put(request, response);
});
});
};
const returnFromCache = (request) => {
return caches.open('cc-offline').then((cache) => {
return cache.match(request).then((matching) => {
return (!matching || matching.status == 404) ? cache.match('offline.html') : matching
});
});
};
I keep getting this error in the console log
Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': Cannot construct a Request with a Request object that has already been used.
I tried changing my service worker but it doesn't work
self.addEventListener('install', (event) => event.waitUntil(preLoad()));
const preLoad = function () {
return caches.open('cc-offline').then((cache) => {
return cache.addAll(['/offline.html', '/index.html']);
});
}
self.addEventListener('fetch', (event) => {
event.respondWith(checkResponse(event.request).catch(function () {
return returnFromCache(event.request)
}));
event.waitUntil(addToCache(event.request));
});
const checkResponse = (request) => {
return new Promise((fulfill, reject) => {
fetch(request).then((response) => {
(response.status !== 404) ? fulfill(response) : reject()
}, reject)
});
};
const addToCache = (request) => {
return caches.open('cc-offline').then((cache) => {
return fetch(request).then((response) => {
return cache.put(request, response);
});
});
};
const returnFromCache = (request) => {
return caches.open('cc-offline').then((cache) => {
return cache.match(request).then((matching) => {
return (!matching || matching.status == 404) ? cache.match('offline.html') : matching
});
});
};
Share
Improve this question
asked May 4, 2019 at 5:58
Julian SanchezJulian Sanchez
1011 silver badge9 bronze badges
1 Answer
Reset to default 3fetch
don't allow you to use a request twice, at least at current version :). Using the same request object in both checkResponse
and addToCache
maybe the case. You can try to clone the request object before calling fetch
as mention in here Why does this code fail to execute 'fetch'?