如何正确使用我们网站上的Contacts API管理联系人?

问题描述 投票:0回答:1

我正在尝试集成Google Contacts API来管理我网站中的联系人。

我已完成以下操作:

  1. 我已经在Google Developer Console中创建了一个应用程序,并将http://localhost:4200添加为URI和授权的重定向URI。
  2. 已启用“联系人API”。
  3. 我在index.html中添加了以下内容(我已经用原始的客户ID代替了{clientID}(当然):
  <script>
    function loadAuthClient() {
      gapi.load('auth2', function() {
        gapi.auth2.init({
          client_id: '{clientID}'
        }).then(() => {
          console.log("success");
        }).catch(err => {
          console.log(err);
        });
      });
    }
  </script>
  <script src="https://apis.google.com/js/platform.js?onload=loadAuthClient" async defer></script>
  <meta name="google-signin-client_id" content="{clientID}">
  1. 成功使用以下方式登录:
    gapi.auth2.getAuthInstance().signIn().then(() => {
      console.log("Logged in")
    }).catch(err => {
      console.log(err);
    });
  1. 尝试使用以下方法获取联系人:
    var user = gapi.auth2.getAuthInstance().currentUser.get();
    var idToken = user.getAuthResponse().id_token;
    var endpoint = `https://www.google.com/m8/feeds/contacts/`;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', endpoint + '?access_token=' + encodeURIComponent(idToken));
    xhr.setRequestHeader("Gdata-Version", "3.0");
    xhr.onreadystatechange = function () {
      if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
        window.alert(xhr.responseText);
      }
    };
    xhr.send();

但是我遇到了错误:

从原点https://www.google.com/m8/feeds/contacts/?access_token=到'http://localhost:4200 {我已删除访问令牌}的XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否'Access-Control-允许来源的标头出现在请求的资源上。

有人可以指导我哪里出问题了吗?

google-authentication google-contacts-api
1个回答
0
投票

[我怀疑您需要为正在使用的OAuth客户端将http://localhost:4200添加到“授权的JavaScript来源”列表中。

编辑OAuth 2.0 Client ID,然后将URI添加到Javascript起源中,如下所示:OAuth client with a Javascript origin

该页面的另一部分,授权重定向URI,仅允许将OAuth流重定向回您的Web应用程序。通常,您的网络应用服务器实际上会使用这些API,因此Google不会自动允许CORS访问这些API以保持安全。

© www.soinside.com 2019 - 2024. All rights reserved.