Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The Image tag with `crossOrigin="Anonymous"` can't load success from S3

In javascript

const image = new Image() image.crossOrigin = 'Anonymous' image.src = 'https://s3.amazonaws.com/ch-static-beta/avatar/user/1a8fdd22d5ec11e784da0e28350150f71512059569.png'

will get an error of enter image description here

And the http header is enter image description here

But when I use the curl and with this request header, the response will success. like this.enter image description here

like image 399
xsong Avatar asked Mar 27 '18 01:03

xsong


1 Answers

That's a caching issue, and a chrome bug*:

*Closed as WONT-FIX, chrome devs said it isn't a bug per se, it's a misconfiguration of the server which should send the allow origin headers to any requests... A related bug report, also closed as WONT-FIX.

You probably already had made a request to this image without requesting for the CORS headers.

When you perform the second request, the browser will wrongly reuse the cached response.

var rand = '?'+Math.random();
var no_cors = new Image();
no_cors.onload = loadCORS;
no_cors.src = 'https://s3.amazonaws.com/ch-static-beta/avatar/user/1a8fdd22d5ec11e784da0e28350150f71512059569.png' + rand;


function loadCORS(){
  var with_cors = new Image();
  with_cors.crossOrigin = 'anonymous';
  with_cors.src = no_cors.src;
  with_cors.onload = function(){console.log('loaded');};
  with_cors.onerror = function(){console.error('failed');};
}

So for a fix: [...] Configure your S3 so that it always sends the cross-origin headers.*
For a workaround, always load the crossOrigin version.
For a temp fix, disable caching.

*It seems it's not possible to setup S3 to do so, see this excellent answer by Michael - sqlbot, which also provides other server-side workarounds.

like image 65
Kaiido Avatar answered Oct 25 '22 07:10

Kaiido