6

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.

franco phong
  • 2,219
  • 3
  • 26
  • 43

1 Answers1

15

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.

franco phong
  • 2,219
  • 3
  • 26
  • 43
  • Please post back if you found a better solution. Just ran into this myself. I had even cleared 'all' cache in Chrome, but apparently this aspect is still cached. Thanks Chrome for waisting an hour of my life. – adammenges Feb 26 '18 at 18:53
  • You're my hero. I've been running in circles changing up CORS configurations and not making any progress. Didn't realize browser caching is screwing things up! – Uri Merhav Mar 04 '19 at 21:00