【问题标题】:Images from S3 not working with Service Worker来自 S3 的图像无法与 Service Worker 一起使用
【发布时间】:2016-10-12 02:34:23
【问题描述】:

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

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

这是软件代码:

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 的图像上,所有其他图像都按预期工作。有谁知道怎么回事?

【问题讨论】:

    标签: javascript service-worker


    【解决方案1】:

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

    如果您启用了CORS in S3add the crossorigin attribute to your <img> tags,那么您的响应应该都启用了CORS。

    或者,您可以通过不在 addToCache() 函数中检查 response.ok 的值来解决您收到不透明响应的问题 - 对于不透明响应,它始终为 false。这意味着您可能最终会向缓存添加 4xx 或 5xx 错误响应,而不是有效的图像响应,但这是您在缓存不透明响应时所面临的风险。

    【讨论】:

      猜你喜欢
      • 2020-05-26
      • 2020-04-24
      • 2018-06-25
      • 1970-01-01
      • 2021-03-12
      • 2016-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多