【问题标题】:S3 Access-Control-Allow-OriginS3 访问控制允许来源
【发布时间】:2022-01-09 02:57:46
【问题描述】:

我从我的 rails 应用程序中将图像嵌入到第 3 方网站时出错。图像通过 activeStorage 进行管理,并从 s3 存储桶提供。

图像在 chrome/edge/safari 中不显示。在 Firefox 中工作。

我在控制台中收到错误

Access to image at [s3 url] (redirected from [app url]) has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

图像包含在应用程序中,如下所示:

<img alt="pose for outfit" class="pose-image" crossorigin="anonymous" src="https://app.puctto.com/rails/active_storage/blobs/redirect/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBBc2tFIiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--af1951d452ca9460b7e007f20d5157b34690d653/model-pose.jpg">

我已将 cors 策略添加到我的存储桶中

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "HEAD"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [],
        "MaxAgeSeconds": 3000
    },
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "PUT",
            "POST",
            "GET"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [],
        "MaxAgeSeconds": 3000
    }
]

我添加了一个存储桶策略,正如其他地方建议的那样作为修复。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:GetObject",
                "s3:GetObjectVersion"
            ],
            "Resource": "arn:aws:s3:::puctto-storage/*"
        }
    ]
}

这还没有解决问题。如何正确发送 CORS 标头?如何让图像正确显示?

要查看错误,请转到: https://www.puctto.me/collections/all 点击右下角的P。应该有一个模型图像,但在 chrome、edge 和 safari 中没有图像显示并且控制台给出了错误。

【问题讨论】:

  • 在页面上重新加载图像显示。浏览器重启后,图片再次加载失败。
  • 更新 CORS 配置后尝试清理浏览器缓存。
  • @yetanothersourav - 感谢您对此进行调查,但我已清除缓存 - 问题仍然存在。
  • @yetanothersourav - 具体来说,如果我清除缓存并重新加载,图像会显示。但是重新启动并重新访问该站点,问题再次出现。

标签: amazon-s3 cors rails-activestorage


【解决方案1】:

如果您以编程方式获取图像,请尝试此方法:

Cross-origin requests AJAX requests to AWS S3 sometimes result in CORS error

    const response = await fetch(url, {
      cache: 'no-cache',
    });

【讨论】:

  • 您好,谢谢。我不是。它只是一个图像标签
猜你喜欢
  • 2020-10-31
  • 2012-07-04
  • 1970-01-01
  • 2014-06-18
  • 1970-01-01
  • 1970-01-01
  • 2016-01-02
  • 2017-12-15
相关资源
最近更新 更多