A
A
Asker18882020-05-03 16:20:09
JavaScript
Asker1888, 2020-05-03 16:20:09

How to continue the request to the server if the requested item is missing in cashStorage?

Good afternoon!
I deal with service workers, the following question arose:
If I correctly understood the principle of operation, then sw intercepts each request to the server and checks for the presence of a request in the cache. If not, it should in theory return control to the original request in order for it to be executed, but in my case this does not happen. The request simply returns an error (TypeError: Failed to fetch from actions.js).
I don’t understand how you need to specify that in the absence of a cache, you need to make a real request to the server?

I am guided by this article .

Create React App. Server requests are processed via fetch in redux-thunk.

sw code:

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE).then((cache) =>
      cache.addAll(cacheData))
  );
});

self.addEventListener('fetch', (event) => {
  event.respondWith(fromCache(event.request));
  event.waitUntil(
    update(event.request)
      .then(refresh)
      .catch((error) => console.error('Failed from fetch: ', error))
  );
});

function fromCache(request) {
  return caches.open(CACHE).then((cache) =>
    cache.match(request).then((matching) =>
      matching || Promise.reject('no-match')
    ));
}

function update(request) {
  return caches.open(CACHE).then((cache) =>
    fetch(request).then((response) =>
      cache.put(request, response.clone()).then(() => response).catch((error) => console.error('Error from update: ', error))
    )
  );
}

function refresh(response) {
  console.log('RESPONSE', response);
  return self.clients.matchAll().then((clients) => {
    clients.forEach((client) => {
      const message = {
        type: 'refresh',
        url: response.url,
        eTag: response.headers.get('ETag')
      };
      client.postMessage(JSON.stringify(message));
    });
  }).catch((error) => console.error('Error from refresh: ', error));
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question