首页 > 解决方案 > javascript 获取 S3 存储桶上资源的问题(由 Cloudfront 提供)

问题描述

我正在配置一个简单的 javascript 获取 S3 存储桶上由 Cloudfront 提供的资源。这不仅适用于本地主机,而且适用于任何其他来源,请参阅 AWS 的响应:

Response: Access to image at from origin 'http://localhost:3000 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

在与 AWS 支持人员交谈后,一切都以正确的方式配置:S3 存储桶中的 CORS,云端分发中的标头请求,包括“基于选定请求标头的缓存”-标头白名单中的以下内容。

Cloudfront 似乎不提供 Access-Control-Allow-Origin 标头。有人解决了通过云端从 S3 简单获取的问题吗?

These are response headers:
accept-ranges: bytes
content-length: 100286
content-type: image/jpg
date: Mon, 05 Oct 2020 18:36:18 GMT
etag: "81e0932668804433487c4ab834e8a017"
last-modified: Fri, 08 May 2020 01:55:46 GMT
server: AmazonS3
status: 200
via: 1.1 4ba9d3779ca8afc198240a34dffb07c4.cloudfront.net (CloudFront)
x-amz-cf-id: 8YQXChq71yTXuTK8OQ4TwtHIYA2oEgqdXvWnUJiU0CHDIxwMiV2iyQ==
x-amz-cf-pop: DUS51-C1
x-amz-version-id: wceb3chundfHz43URYzzrTyIBKh7bisb
x-cache: Miss from cloudfront

这是 javascript 下载代码的示例:

        const img = new Image();
        // img.crossOrigin = 'Anonymous';  // This tells the browser to request cross-origin access when trying to download the image data.
        // ref: https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image#Implementing_the_save_feature 

        img.setAttribute('crossorigin', 'anonymous');
        img.src = image.sampleUrl;
        img.onload = () => {
          // create Canvas
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          canvas.width = img.width;
          canvas.height = img.height;
          ctx.drawImage(img, 0, 0);
          // create a tag
          const a = document.createElement('a');
          a.download = 'preview.jpg';
          a.href = canvas.toDataURL('image/jpg');
          a.click();
        };
      };```

[1]: https://i.stack.imgur.com/f6EoF.png

[![cloudfront config][1]][1]





标签: javascriptamazon-web-servicesamazon-s3fetchamazon-cloudfront

解决方案


没有任何帮助,AWS 上的所有设置都已根据文档完成。我终于用这个答案解决了这个问题,作为一种解决方法来为请求的资源添加一些结尾:

URLs would be something like:

http://.../some.png?http_mysite.com
https://.../some.png?https_mysite.com

我从这个答案中得到了这个:

正确的 S3 + Cloudfront CORS 配置?


推荐阅读