我试图通过ajax从亚马逊服务器获取图像。该服务器配置为返回Access-Control-Allow-Origin: *
标头。
问题在于,当我从终端发出请求时,我看到回复很好。
但是当我从浏览器处执行AJAX请求时,我被阻止了,而且我没有在响应中看到该标题。
终端请求:
➜ ~ curl -sI -H "Origin: google.com" -H "Access-Control-Request-Method: GET" http://my-domain/my-image.jpg
HTTP/1.1 200 OK
Content-Type: image/jpeg
Content-Length: 595284
Connection: close
Date: Thu, 13 Aug 2015 12:28:02 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST
Access-Control-Max-Age: 3000
Content-Disposition: attachment; filename="Hydrangeas.jpg"
Last-Modified: Thu, 13 Aug 2015 07:00:21 GMT
x-amz-version-id: null
ETag: "bdf3bf1da3405725be763540d6601144"
Server: AmazonS3
Age: 4132
X-Cache: Hit from cloudfront
Via: 1.1 b7b782c917cd62c6605a1684c071a774.cloudfront.net (CloudFront)
X-Amz-Cf-Id: 7t1gB74LHHWEIXcl_ml6pWC9voDrfSakCMUJ2KeAjMYZ-37aZYmPcg==
当我尝试使用Chrome / FF(没有尝试过其他人)时,我会看到规范的错误消息,当我查看网络标签时,我看不到ACAA标题:
XMLHttpRequest cannot load ***. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '***' is therefore not allowed access.
这是我用来尝试获取图片的代码:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState === 4 && this.status === 200){
// never gets here, status is always 0 from the block
}
}
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();