本文介绍了带有`crossOrigin =" Anonymous"的Image标记无法从S3加载成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




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



会得到
的错误



http标题是
*:



您可能已经在不请求CORS头文件的情况下对这个图片发出了请求。



当你perfo第二个请求,浏览器将错误地重复使用缓存的响应。



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

因此,对于修复:[...] *

有关解决方法,总是加载crossOrigin版本。

对于临时修复,请禁用缓存。



*似乎无法设置S3来执行此操作,请参阅通过 Michael - sqlbot ,它也提供了其他服务器端解决方法。


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

And the http header is

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

解决方案

That's a caching issue, *:

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 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: [...] *
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.

这篇关于带有`crossOrigin =" Anonymous"的Image标记无法从S3加载成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 14:26