franco phong
franco phong

Reputation: 2219

XMLHttpRequest and S3, CORS error

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.

Upvotes: 6

Views: 5494

Answers (1)

franco phong
franco phong

Reputation: 2219

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.

Upvotes: 14

Related Questions