简体   繁体   English

XMLHttpRequest和S3,CORS错误

[英]XMLHttpRequest and S3, CORS error

I host my photos on S3 bucket. 我在S3桶上托管我的照片。 I added CORS configuration for S3 bucket: 我添加了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>

In my html page, I tried to save image, so I am using the library: https://github.com/tsayen/dom-to-image 在我的html页面中,我试图保存图像,所以我使用的是库: https//github.com/tsayen/dom-to-image

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

I got the CORS error: 我收到了CORS错误:

XMLHttpRequest cannot load http://s3/bucket/path/image.png . XMLHttpRequest无法加载http://s3/bucket/path/image.png No 'Access-Control-Allow-Origin' header is present on the requested resource. 请求的资源上不存在“Access-Control-Allow-Origin”标头。

Any Suggestion is appreciated. 任何建议表示赞赏。

After long debugging, I found the core issue. 经过长时间的调试,我找到了核心问题。 All S3 CORS configuration were corrected, nothing to do with the S3. 所有S3 CORS配置都已更正,与S3无关。 The issue came from the browser caching. 问题来自浏览器缓存。 This annoying caching prevented S3 response Access-Control-Allow-Origin' header in response, and that's why it caused the error. 这个令人讨厌的缓存阻止了S3响应Access-Control-Allow-Origin'标头作为响应,这就是它导致错误的原因。

The solution: (it's a hacky solution but it worked) I added one line of code in method getAndEncode of dom-to-image.js to prevent the browser caching. 解决方案:(这是一个hacky解决方案,但它工作)我在dom-to-image.js的方法getAndEncode中添加了一行代码,以防止浏览器缓存。

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

        return new Promise(function (resolve) {
            ....
            request.open('GET', url, true);
...

Again, this is a hacky way, I am still opening for any better solution. 再次,这是一个hacky方式,我仍然打开任何更好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM