客户端检索Google联系人图片 [英] Client-side retrieval of Google Contact pictures

查看:146
本文介绍了客户端检索Google联系人图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google JavaScript API在网络应用程序中提取google联系人,我想检索其图片.

I'm fetching google contacts in a webapp using the Google JavaScript API and I'd like to retrieve their pictures.

我正在做类似的事情(大大简化):

I'm doing something like this (heavily simplified):

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中都遇到此错误:

But I'm getting this error both in Chrome and Firefox:

跨域请求被阻止:同源起源"策略不允许读取 https://www.google.com/m8/feeds/photos/media/<user_email >/< some_contact_id>?v = 3.0& access_token =<混淆.可以通过将资源移至同一域或启用CORS来解决此问题.

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.

从feeds/photos端点查看响应标头时,我看到未发送Access-Control-Allow-Origin: *,因此出现了CORS错误.

When looking at the response headers from the feeds/photos endpoint, I can see that Access-Control-Allow-Origin: * is not sent, hence the CORS error I get.

请注意,Access-Control-Allow-Origin: *是在到达feeds/contacts端点时发送的,因此允许跨域请求.

Note that Access-Control-Allow-Origin: * is sent when reaching the feeds/contacts endpoint, hence allowing cross-domain requests.

这是一个错误,还是我错过了他们的文档中的某些内容?

Is this a bug, or did I miss something from their docs?

推荐答案

尚无法评论,因此此答案…

Not able to comment yet, hence this answer…

很显然,您已经在 Google开发人员控制台中设置了正确的客户端ID和JavaScript来源.

Obviously you have already set up the proper client ID and JavaScript origins in the Google developers console.

域共享联系人API 似乎不起作用如广告中所宣传的那样,并且在您请求JSONP数据时仅遵守其CORS承诺(您的代码表明您使用JSON获得了输入数据).对于JSON格式,API将access-control-allow-origin设置为*,而不是您为项目列出的JavaScript来源.

It seems that the domain shared contacts API does not work as advertised and only abides by its CORS promise when you request JSONP data (your code indicates that you got your entry data using JSON). For JSON format, the API sets the access-control-allow-origin to * instead of the JavaScript origins you list for your project.

但是从今天(2015-06-16)开始,如果您尝试发布具有不同数据类型(例如atom/xml)的GETPOST…,则Google API不会完全设置access-control-allow-origin,因此您的浏览器将拒绝您访问数据的请求(错误405).

But as of today (2015-06-16), if you try to issue a GET, POST… with a different data type (e.g. atom/xml), the Google API will not set the access-control-allow-origin at all, hence your browser will deny your request to access the data (error 405).

这显然是一个错误,可以防止对共享联系人API进行任何编程性使用,而只是简单地列出条目:不再可以创建,更新,删除条目或访问照片.

This is clearly a bug, that prevents any programmatic use of the shared contacts API but for simple listing of entries: one can no longer create, update, delete entries nor access photos.

如果我弄错了,请纠正我(我希望我是);如果您知道向Google提交此错误的最佳方法,请发表评论或进行编辑.

Please correct me if I'm mistaken (I wish I am); please comment or edit if you know the best way to file this bug with Google.

注意,为了完整起见,这是我用来访问联系人(需要jQuery)的代码框架.

Note, for the sake of completeness, here's the code skeleton I use to access contacts (requires jQuery).

    <button id="authorize-button" style="visibility: hidden">Authorize</button>
    <script type="text/javascript">
        var clientId = 'TAKE-THIS-FROM-CONSOLE.apps.googleusercontent.com',
            apiKey = 'TAKE-THAT-FROM-GOOGLE-DEVELOPPERS-CONSOLE',
            scopes = 'https://www.google.com/m8/feeds';
        // Use a button to handle authentication the first time.
        function handleClientLoad () {
            gapi.client.setApiKey ( apiKey );
            window.setTimeout ( checkAuth, 1 );
        }
        function checkAuth() {
            gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
        }
        function handleAuthResult ( authResult ) {
            var authorizeButton = document.getElementById ( 'authorize-button' );
            if ( authResult && !authResult.error ) {
                authorizeButton.style.visibility = 'hidden';
                var cif = {
                    method: 'GET',
                    url:  'https://www.google.com/m8/feeds/contacts/mydomain.com/full/',
                    data: {
                        "access_token": authResult.access_token,
                        "alt":          "json",
                        "max-results":  "10"
                    },
                    headers: { 
                        "Gdata-Version":    "3.0"    
                    },
                    xhrFields: {
                        withCredentials: true
                    },
                    dataType: "jsonp"
                };
                $.ajax ( cif ).done ( function ( result ) {
                        $ ( '#gcontacts' ).html ( JSON.stringify ( result, null, 3 ) );
                } );
            } else {
                authorizeButton.style.visibility = '';
                authorizeButton.onclick = handleAuthClick;
            }
        }
        function handleAuthClick ( event ) {
            gapi.auth.authorize ( { client_id: clientId, scope: scopes, immediate: false }, handleAuthResult );
            return false;
        }
    </script>
    <script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
    <pre id="gcontacts"></pre>

如果将cif.data.alt替换为atom,并且/或者将cif.dataType替换为xml,则会收到臭名昭著的错误405.

If you replace cif.data.alt by atom and/or cif.dataType by xml, you get the infamous error 405.

ps: cif 当然与 查看全文

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