access-control-allow-origin header 从 objects 中丢失,即使在 Digitalocean Spaces UI 中添加 CORS 设置后也是如此

access-control-allow-origin header missing from objects even after adding CORS settings in Digitalocean Spaces UI

我在 DigitalOcean Spaces UI 中添加了 CORS 配置,如下所示:

我的浏览器 object 请求仍然没有收到 access-control-allow-origin header。

当 object 从我的后端上传时,“public-read”被设置为 ACL。

我期待,当 object(在我的例子中是图像)请求是从浏览器中的我的 Web 应用程序发出时,它的响应 headers 应该有 access-control-allow-origin: http://my.machine.localhost

当 canvas 组件具有来自 non-origin 个来源的图像时,HTML canvas toDataURL() 提出了硬性要求。

首先是localhost问题

DO (DigitalOCean) 不允许您在 CORS 源字段中配置本地主机。为此,您可以更新 /etc/hosts 为您的本地主机指定一个可接受的名称。我有

127.0.0.1        my.machine.localhost

这样可以很容易地在 DO 空间 CORS 设置中进行配置,并且在浏览器中点击 my.machine.localhost 应该会在本地主机上 运行ning 打开你的应用程序(我 运行 我的应用程序在端口上80).

二、CORSheaders

在解决问题或必须多次清除缓存之前禁用 CDN。使用 curlhttpie 或类似的东西来测试,因为浏览器倾向于缓存 objects.

我假设 objects 是使用 public-read ACL 上传的。

现在用 curl 或 httpie 检查请求和响应 headers。

$ http -v https://***.***.digitaloceanspaces.com/static/images/logo.png

这是棘手的部分 - 即使您配置了 CORS,响应也不会 access-control-allow-origin header。为了让它工作,您需要在您的请求中设置 Origin header,它需要与您的存储桶的 DO Spaces UI 中配置的 at-least 之一相匹配。

$ http -v https://***.***.digitaloceanspaces.com/static/images/logo.png "Origin:http://my.machine.localhost"

这将 return access-control-allow-originaccess-control-allow-methods 根据您的配置。


DO 空间实现与 AWS S3 相同的 API。所以卡的时候最好找找S3文档。我在 AWS S3 CORS 文档中找到了这个 https://docs.aws.amazon.com/AmazonS3/latest/userguide/cors-troubleshooting.html

If the header is missing, Amazon S3 doesn't treat the request as a cross-origin request, and doesn't send CORS response headers in the response.

网上有很多教程推荐使用 s3cmd 并使用通配符设置 CORS * - 在做这些之前请三思,因为它非常不安全。