【问题标题】:Service worker and caching images from other domain (aws s3) : "will not cache opaque responses"服务工作者和缓存来自其他域(aws s3)的图像:“不会缓存不透明的响应”
【发布时间】:2019-02-04 15:49:54
【问题描述】:

我正在尝试使站点离线可用并缓存从 AWS S3 检索到的图像。我正在使用工作箱库:

var CACHE_VERSION = '2019-02-03'

// cf https://developers.google.com/web/tools/workbox/guides/get-started
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.6.1/workbox-sw.js')

workbox.routing.registerRoute(
  // Cache image files
  /https:\/\/s3\.amazonaws\.com\/myproject\/img\/.*\.(?:png|jpg|jpeg|svg)/,
  // Use the cache if it's available
  workbox.strategies.cacheFirst({
    // Use a custom cache name
    cacheName: 'image-cache-' + CACHE_VERSION,
    plugins: [
      new workbox.expiration.Plugin({
        // Cache for a maximum of a week
        maxAgeSeconds: 7 * 24 * 60 * 60,
      })
    ],
  })
)

这会导致控制台中的工作箱出现以下错误消息:

https://s3.amazonaws.com/myproject/img/icon.png”的响应是不透明的响应。默认情况下,您使用的缓存策略不会缓存不透明的响应。

我已经为这些图像添加了 crossorigin='anonymous' 属性,并且我在 AWS S3 上有了这个 CORS 配置:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
  </CORSRule>
  <CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
  </CORSRule>
</CORSConfiguration>

我没有正确使用 CORS 吗?如何使响应成为正常响应而不是不透明响应?

【问题讨论】:

  • 如果您还不知道,我们有一个关于如何Handle Third Party Requests 的官方文档。在文档中的某个位置,您将被重定向到那里,您将能够了解更多关于 opaque responses 应用于它的信息。
  • @MαπμQμαπkγVπ.0 我知道那个文档,但这不是我想要的。我不想缓存不透明的响应,我希望响应不是不透明的。

标签: service-worker progressive-web-apps workbox


【解决方案1】:

好吧,这是一个愚蠢的错误。我在做正确的事,但 crossorigin="anonymous" 属性是在某些图像上设置的,而不是在其他图像上。在所有图像上正确设置它可以解决问题。

我正在开发的网站以一种不同寻常的方式使用了背景图像的组合,这使得调试变得更加困难。顶部的图像正确具有 crossorigin 属性,但隐藏在其下的其他图像没有它,并且导致一切失败,包括顶部图像的显示,在离线模式下正确缓存。愚蠢的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 2016-12-07
    • 2020-01-08
    • 1970-01-01
    相关资源
    最近更新 更多