javascript - 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]
解决方案
没有任何帮助,AWS 上的所有设置都已根据文档完成。我终于用这个答案解决了这个问题,作为一种解决方法来为请求的资源添加一些结尾:
URLs would be something like:
http://.../some.png?http_mysite.com
https://.../some.png?https_mysite.com
我从这个答案中得到了这个:
推荐阅读
- python - 如何使用正则表达式匹配包含横线的字符串?
- c# - 将leaft浏览器转换为硒驱动程序
- html - Angular:输入元素上的 *ngIf 标记导致它未定义。无法从输入字段中读取值
- javascript - 自动完成下拉菜单 - 添加时间延迟并等待至少 3 个字符输入
- deeplearning4j - Deeplearning4j 重复方法调用
- python - Keras CNN 架构
- javascript - 如何在每个矩形端点中绘制圆圈
- sql-server - MS SQL Connect 给出错误 mssql: A SQL editor must have focus
- .net-core - Add-Migration 或 dotnet ef 迁移添加
- javascript - 角度变化检测 zone.js