带有`crossOrigin =" Anonymous"的Image标记无法从S3加载成功 [英] The Image tag with `crossOrigin="Anonymous"` can't load success from S3

查看:247
本文介绍了带有`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标题是
*:

*已关闭作为WONT-FIX,chrome开发人员表示它本身并不是一个bug,它是服务器的错误配置,应该将允许源头部发送给任何请求......相关错误报告,也作为WONT-FIX关闭。



您可能已经在不请求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');};}  

因此,对于修复:[...] 配置您的S3,以便始终发送跨源标头。 *

有关解决方法,总是加载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, 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.

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

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆