Google Calendar API javascript错误:原因不匹配

Han*_*ali 5 javascript oauth google-calendar-api

我正在处理一个我在此处找到的简单JavaScript代码:http://googleappsdeveloper.blogspot.com/2011/12/using-new-js-library-to-unlock-power-of.html

它基本上获取了谷歌日历的身份验证,并检索其中包含的事件列表.我已经注册了我的Web应用程序并获得了客户端ID和API密钥.

我正面临这样的错误:"错误:原因不匹配",我正在使用localhost在本地运行javascript,我也将我的主页在google应用程序注册中设置为localhost.

任何帮助都会非常感激.

代码:

<html>
  <body>
    <div id='content'>
      <h1>Events</h1>
      <ul id='events'></ul>
    </div>
    <a href='#' id='authorize-button' onclick='handleAuthClick();'>Login</a>

    <script>
    var clientId = '506979856128.apps.googleusercontent.com';
var apiKey = 'AIzaSyAGbQAZQU0YNL8hK5EU69exIg7_sOg3JoA';
var scopes = 'https://www.googleapis.com/auth/calendar';

      function handleClientLoad() {
  gapi.client.setApiKey(apiKey);
  window.setTimeout(checkAuth,1);
  checkAuth();
}

function checkAuth() {
  gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true},
      handleAuthResult);
}

function handleAuthResult(authResult) {
  var authorizeButton = document.getElementById('authorize-button');
  if (authResult) {
    authorizeButton.style.visibility = 'hidden';
    makeApiCall();
  } else {
    authorizeButton.style.visibility = '';
    authorizeButton.onclick = handleAuthClick;
   }
}

function handleAuthClick(event) {
  gapi.auth.authorize(
      {client_id: clientId, scope: scopes, immediate: false},
      handleAuthResult);
  return false;
}

function makeApiCall() {
  gapi.client.load('calendar', 'v3', function() {
    var request = gapi.client.calendar.events.list({
      'calendarId': 'primary'
    });

    request.execute(function(resp) {
      for (var i = 0; i < resp.items.length; i++) {
        var li = document.createElement('li');
        li.appendChild(document.createTextNode(resp.items[i].summary));
        document.getElementById('events').appendChild(li);
      }
    });
 });
}
    </script>
    <script src="https://apis.google.com/js/client.js?onload=handleClientLoad">                 </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Mil*_*war 2

我今天遇到了同样的错误来源不匹配。经过一番搜索后我找到了原因。

在创建 Google Api 访问时,我们必须指定Authorized Redirect URIsAuthorized Redirect URIs

现在,如果您从授权重定向URI 中指定的 URI 以外的 URI 调用登录,error:Unknown Origin is thrown

仅供参考:我发现您正在使用 localhost 在本地运行 javascript。这意味着您尚未将 localhost uri 添加到授权重定向 URI。

但不要浪费时间这样做。授权重定向 URI 不会接受 localhost uri。这是由于 Chrome 的同源策略。如果您使用禁用网络安全标志运行 chrome,它也可以在本地工作。