XMLHttpRequest和S3,CORS错误 [英] XMLHttpRequest and S3, CORS error

查看:105
本文介绍了XMLHttpRequest和S3,CORS错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I host my photos on S3 bucket. I added CORS configuration for S3 bucket:

<?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>

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

In my html page, I tried to save image, so I am using the library: https://github.com/tsayen/dom-to-image

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

我收到了CORS错误:

I got the CORS error:

XMLHttpRequest无法加载 http://s3/bucket/path/image.png .请求中不存在"Access-Control-Allow-Origin"标头资源.

XMLHttpRequest cannot load http://s3/bucket/path/image.png. No 'Access-Control-Allow-Origin' header is present on the requested resource.

任何建议都值得赞赏.

推荐答案

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

After long debugging, I found the core issue. All S3 CORS configuration were corrected, nothing to do with the 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.

解决方案:(这是一个骇人听闻的解决方案,但是有效)我在dom-to-image.js的方法 getAndEncode 中添加了一行代码,以防止浏览器缓存.

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.

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.

这篇关于XMLHttpRequest和S3,CORS错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆