XMLHttpRequest和S3,CORS错误

fra*_*ong 4 javascript amazon-s3 cors

我将照片托管在S3存储桶中。我为S3存储桶添加了CORS配置:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
 <AllowedOrigin>*</AllowedOrigin>
 <AllowedMethod>GET</AllowedMethod>
 <ExposeHeader>Accept-Ranges</ExposeHeader>
 <ExposeHeader>Content-Range</ExposeHeader>
 <ExposeHeader>Content-Encoding</ExposeHeader>
 <ExposeHeader>Content-Length</ExposeHeader>
 <ExposeHeader>Access-Control-Allow-Origin</ExposeHeader>
 <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
Run Code Online (Sandbox Code Playgroud)

在我的html页面中,我尝试保存图像,因此我正在使用该库:https : //github.com/tsayen/dom-to-image

domtoimage.toBlob(document.getElementById('my-node'))
.then(function (blob) {
    window.saveAs(blob, 'my-node.png');
});
Run Code Online (Sandbox Code Playgroud)

我收到了CORS错误:

XMLHttpRequest无法加载 http://s3/bucket/path/image.png。所请求的资源上没有“ Access-Control-Allow-Origin”标头。

任何建议表示赞赏。

fra*_*ong 6

经过长时间的调试,我发现了核心问题。已纠正所有S3 CORS配置,与S3无关。问题来自浏览器缓存。这种烦人的缓存阻止了S3响应中的Access-Control-Allow-Origin'标头响应,这就是导致错误的原因。

解决方案:(这是一个hacky解决方案,但是它起作用了)我在getAndEncodedom-to-image.js 方法中添加了一行代码以防止浏览器缓存。

function getAndEncode(url) {
        ...
        url += "?"+(new Date()).getTime(); // this line of code made magic.

        return new Promise(function (resolve) {
            ....
            request.open('GET', url, true);
...
Run Code Online (Sandbox Code Playgroud)

再次,这是一种怪诞的方式,我仍在寻求更好的解决方案。