XMLHttpRequest and S3, CORS error

会有一股神秘感。 提交于 2021-02-19 02:05:45

问题


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>

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');
});

I got the CORS error:

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

Any Suggestion is appreciated.


回答1:


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.

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.



来源:https://stackoverflow.com/questions/43345708/xmlhttprequest-and-s3-cors-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!