【问题标题】:Service worker returning correct response but still getting 'no internet' error服务人员返回正确响应但仍然出现“无互联网”错误
【发布时间】:2019-04-20 15:19:33
【问题描述】:

我正在尝试设置一个服务工作者,以便我的网络应用可以完全离线工作。当我检查 static-v2 的缓存时,我想要的所有资产都在那里。

当我提出请求并在线时,我的 SW 正在正确地执行 fetch 并且没有落入我的 catch 语句中。

但是,当我离线并且进入缓存时,会记录正确的响应,状态为 200,但我收到 chrome 的“无互联网”错误。

另一个有趣的点是,即使我注释掉返回缓存响应的行并仅返回硬编码响应,我仍然会收到“无互联网”错误。

任何帮助找出我的服务人员没有按预期工作的原因将不胜感激。

const CACHENAME = `static-v2`;

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(CACHENAME).then(function(cache) {
      return cache
        .addAll([
          // your list of cache keys to store in cache
          'bundle.js',
          'index.html',
          'manifest.json',
          // etc.
        ])
        .then(() => {
          return self.skipWaiting();
        });
    }),
  );
});

self.onactivate = (evt) => {
  console.log(`on activate - ${CACHENAME}`);

  evt.waitUntil(
    caches.keys().then((cacheNames) => {
      const deleteOldCaches = cacheNames.map((cacheName) => {
        console.log(cacheName);

        if (cacheName != CACHENAME) {
          return caches.delete(cacheName);
        }

        return Promise.resolve();
      });

      return Promise.all(deleteOldCaches);
    }),
  );

  self.clients.claim();
};

self.onfetch = (evt) => {
  evt.waitUntil(
    fetch(evt.request).catch((err) => {
      caches.match(evt.request).then((response) => {
        console.log(evt.request.url, response);

        if (response) return response;

        return new Response('<div><h2>Uh oh that did not work</h2></div>', {
          headers: {
            'Content-type': 'text/html',
          },
        });
      });
    }),
  );

  console.log(`on fetch - ${CACHENAME}`);
};

我正在使用 http-server (https://www.npmjs.com/package/http-server) 托管我的所有资产(inc SW)

【问题讨论】:

    标签: javascript service-worker


    【解决方案1】:

    这是一个简单的错误。

    在您的 fetch 事件处理程序中,您不应该调用 evt.waitUntil。你应该调用 evt.respondWith。

    【讨论】:

    • 谢谢!有趣的是,waitUntil 在某些情况下在某些浏览器中有效,但切换到正确的 respondWith 使其适用于所有内容。
    猜你喜欢
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    相关资源
    最近更新 更多