【发布时间】:2021-01-26 23:43:54
【问题描述】:
我正在配置一个简单的 javascript 获取 S3 存储桶上由 Cloudfront 提供的资源。这不仅适用于 localhost,而且适用于任何其他来源,请参阅 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 标头。 有人解决了通过 cloudfront 从 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]
【问题讨论】:
-
您是否允许使用 OPTIONS 方法?浏览器通常会通过尝试 OPTIONS 请求并查看服务器返回的内容来预检 CORS 请求。如果 Cloudfront 不响应 OPTIONS 请求,可能会导致 CORS 失败
-
是的,我在 CloudFront 中允许了它,但它仍然无法正常工作
-
您是否已将 CORS 配置 XML 添加到您的存储桶并指定应允许的来源?如果没有,请查看此链接docs.aws.amazon.com/AmazonS3/latest/user-guide/…
-
是的,但没有效果。
标签: javascript amazon-web-services amazon-s3 fetch amazon-cloudfront