javascript - Service Worker 中获取 API 错误

标签 javascript service-worker fetch-api

我正在尝试缓存来自 LastFM API 的图像。现在,API 响应本身已缓存良好,并且页面按预期加载,但是没有图像。

查看开发人员控制台,我可以看到一些有关图像检索的错误,如下所示:

Fetch API cannot load http://img2-ak.lst.fm/i/u/300x300/a32cb06bb22bc5d10654a5156fe78cf6.png. The parent document page has been unloaded.

我对服务人员还很陌生,这让我抓狂(不,不是字面上的意思)。

我已经学习了几个教程,这是迄今为止我得到的代码(不相关的代码已被删除)。

var CACHE_NAME = 'WELFORDIAN-CACHE-V2';
var urlsToCache = [
  'https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=**USERNAME**&api_key=6136000ba0899c52db5ebcee77d4be15&format=json'
];

self.addEventListener('install', function(event) {
  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME)
    .then(function(cache) {
      console.log('Opened cache');
      return cache.addAll(urlsToCache);
    })
  );
});

self.addEventListener('fetch', function(event) {
  var reqURL = new URL(event.request.url);
  if (/lst.fm/.test(reqURL)) {
    event.respondWith(lastFMImageResponse(event.request));
  } else {
    event.respondWith(
      caches.match(event.request).then(function(response) {
        if (response) {
          return response;
        }

        var fetchRequest = event.request.clone();

        return fetch(fetchRequest).then(
          function(response) {
            if (!response || response.status !== 200 || response.type !== 'basic') {
              return response;
            }
            var responseToCache = response.clone();

            caches.open(CACHE_NAME)
              .then(function(cache) {
                cache.put(event.request, responseToCache);
              });

            return response;
          }
        );
      }).catch(function(err) {
        return err;
      })
    );
  }
});

function lastFMImageResponse(request) {
  return caches.match(request).then(function(response) {
    if (response) {
      return response;
    }
    return fetch(request).then(function(response) {
      caches.open('lfm-images').then(function(cache) {
        cache.put(request, response);
      });

      return response.clone();
    });
  });
}

我显然做错了什么,但是比我更有经验的人可以解释一下这是什么吗?

最佳答案

问题在于您的网站是 HTTPS,而图像是通过 HTTP 提供的。

混合内容目前不适用于 Service Worker:https://github.com/w3c/webappsec/issues/415 .

关于javascript - Service Worker 中获取 API 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36146374/

相关文章:

javascript - 无法将 JSearch 添加到我的项目中

angular - 如何在 Angular 中读取当前 PWA 的版本哈希?

javascript - (未知): #2514: An unknown error occurred when fetching the script. [服务人员]

javascript - 从 Fetch 中捕获 200 OK 以外的响应

javascript - 以编程方式更新哈希时禁用 hashchange 监听器 (jQuery BBQ)

javascript - 如何在启用拖放的 div 中启用鼠标拖动

javascript - 渐进式 Web 应用程序上的缓存版本控制

unit-testing - React Native-在单元测试中模拟FormData

javascript - 使用 fetch 检索数据时,Vue JS 组件没有反应

javascript - 预期的,但在带有默认参数的 JS 函数的 netbeans 警告中发现 =