正确地从Workbox Service Worker获取缓存的响应

时间:2018-08-31 15:08:52

标签: fetch

我总体上在对工作箱和服务人员进行试验。我尝试对API调用使用NetworkFirst Strategy。控制台似乎按预期方式工作,但是我无法显示来自Service Worker的缓存响应。使用CacheFirst时也会发生同样的情况,但我的dom渲染脚本未收到响应。我想念什么吗?

importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js');`
if (workbox) {
  console.log(`Yay! Workbox is loaded `);

  workbox.precaching.precacheAndRoute([]);

  const cacheName = 'collection';
  workbox.routing.registerRoute(
    new RegExp('http://13.232.112.165/api/'),
    workbox.strategies.networkFirst()
  );


/*
  const bgSyncPlugin = new workbox.backgroundSync.Plugin('post-req-queue', {
    maxRetentionTime: 24 * 60 // Retry for max of 24 Hours
  });

  workbox.routing.registerRoute(
    new RegExp("http://13.232.112.165/api/"),
    workbox.strategies.networkOnly({
      plugins: [bgSyncPlugin]
    }),
    'POST'
  );

  workbox.routing.registerRoute(
    new RegExp("http://13.232.112.165/api/"),
    workbox.strategies.networkOnly({
      plugins: [bgSyncPlugin]
    }),
    'PUT'
  );

  workbox.routing.registerRoute(
    new RegExp("http://13.232.112.165/api/"),
    workbox.strategies.networkOnly({
      plugins: [bgSyncPlugin]
    }),
    'DELETE'
  );
*/
} else {
  console.log(`Boo! Workbox didn't load `);
}`

This is when there is normal network This is when there is no internet 我的Api呼叫如下:

   async function getAccounts() {
    url = backend_uri+"accounts";
    try{
        var jsonResponse = await fetch(url, {headers: {
            'Authorization' : "Token "+localStorage.getItem('user-token')
        }});
        const json = await jsonResponse.json();
        const accounts = await json;

        let renderString = "";
        await accounts.forEach(element => {
            renderString = renderString + `<div class='card'><div class='card-body'><strong>${element.name}</strong></div></div>`        
        });
        containerElement.innerHTML += renderString;
    }catch(e) {
        console.log(e);
    }
}

PWA中的api调用应该有所不同吗?

1 个答案:

答案 0 :(得分:0)

(我不认为您的问题与Workbox或PWA有关;它似乎与使用Fetch API有关。)

我在您的代码中看到了一些额外的await和其他一些问题;你可以尝试以下吗?

async function getAccounts() {
  const url = `${backend_uri}accounts`;

  const response = await fetch(url, {
    headers: {
      'Authorization' : "Token "+localStorage.getItem('user-token')
    },
  });

  const accounts = await response.json();

  const divs = accounts.map(account => `<div class='card'>
  <div class='card-body'>
    <strong>${account.name}</strong>
  </div>
</div>`);

  containerElement.innerHTML += divs.join('');
}