S3中的图片未与Service Worker

时间:2016-10-10 17:37:12

标签: javascript service-worker

我正在将我们的一个网站变成PWA。它有很多来自S3的图像因以下控制台警告而失败:

The FetchEvent for "[image url]" resulted in a network error response: an object that was not a Response was passed to respondWith().

这是SW代码:

self.addEventListener('fetch', event => {

  function onFetch (event) {
    // Determine type of asset
    var request = event.request,
        acceptHeader = request.headers.get('Accept'),
        resourceType = 'static';

    if(acceptHeader.indexOf('text/html') !== -1) {
      resourceType = 'content';
    } else if(acceptHeader.indexOf('image') !== -1) {
      resourceType = 'image';
    }

    // Network first for HTML and images
    if(resourceType === 'content' || resourceType === 'image') {
      event.respondWith(fetch(request)
        .then(response => addToCache(request, response)) // read through caching
        .catch(() => fetchFromCache(event))
        .catch(() => offlineResponse(resourceType))
      )
    }
  }

  onFetch(event);

});

function addToCache(request, response) {

  if(response.ok) { // only 200s
    var copy = response.clone(); // Because responses can only be used once
    caches.open(cacheName)
      .then(cache => {
        cache.put(request, copy);
      });

    return response;
  }

}

function fetchFromCache (event) {

  return caches.match(event.request)
    .then(response => {
      if(!response) {
        // A synchronous error that will kick off the catch handler
        throw Error('${event.request.url} not found in cache');
      }
    return response;
  });

}

这仅适用于来自S3的图像,其他所有图像都按预期工作。任何人都知道发生了什么?

1 个答案:

答案 0 :(得分:2)

我的猜测是来自S3的图像响应是不透明的。 (见:What limitations apply to opaque responses?

如果您启用了CORS in S3add the crossorigin attribute to your <img> tags,则您的回复都应启用CORS。

或者,您可以通过不检查response.ok函数中addToCache()的值来解决您获得不透明响应的事实 - 对于不透明的响应,它总是错误的。这意味着可能最终会向缓存添加4xx或5xx错误响应而不是有效的图像响应,但这是在缓存不透明响应时运行的风险。