我正在使用 Google JavaScript API 在 web 应用程序中获取 google 联系人,我想检索他们的图片。
我正在做这样的事情(大大简化):
var token; // let's admit this is available already
function getPhotoUrl(entry, cb) {
var link = entry.link.filter(function(link) {
return link.type.indexOf("image") === 0;
}).shift();
if (!link)
return cb(null);
var request = new XMLHttpRequest();
request.open("GET", link.href + "?v=3.0&access_token=" + token, true);
request.responseType = "blob";
request.onload = cb;
request.send();
}
function onContactsLoad(responseText) {
var data = JSON.parse(responseText);
(data.feed.entry || []).forEach(function(entry) {
getPhotoUrl(e, function(a, b, c) {
console.log("pic", a, b, c);
});
});
}
但是我在 Chrome 和 Firefox 中都遇到了这个错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.google.com/m8/feeds/photos/media/<user_email>/<some_contact_id>?v=3.0&access_token=<obfuscated>. This can be fixed by moving the resource to the same domain or enabling CORS.
查看来自提要/照片端点的响应 header 时,我可以看到
Access-Control-Allow-Origin: *
没有发送,因此我得到了 CORS 错误。请注意
Access-Control-Allow-Origin: *
到达 feeds/contacts
时发送端点,因此允许跨域请求。这是一个错误,还是我错过了他们文档中的某些内容?
最佳答案
假设您只需要“个人资料图片”,尝试将对该图片的请求直接移动到 HTML 中,方法是将完整 URL 设置为 src
<img>
的元素标签(末尾带有 ?access_token=<youknowit>
)。
例如。使用 Angular.js
<img ng-src="{{contact.link[1].href + tokenForImages}}" alt="photo" />
总体而言,关于 CORS,似乎有很多地方从 JS 访问 API 没有按预期工作。
希望这可以帮助。
关于oauth - 客户端检索 Google 联系人图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21238213/