2012-11-18 41 views
5

我工作的一個簡單的JavaScript代碼,我發現這裏:http://googleappsdeveloper.blogspot.com/2011/12/using-new-js-library-to-unlock-power-of.html谷歌日曆API JavaScript錯誤:產地不匹配

它基本上獲得認證的谷歌日曆和檢索包含的事件列表。我已經註冊了我的Web應用程序並獲得了客戶端ID和API密鑰。

我面對這個錯誤:「錯誤:來源不匹配」,我在本地使用本地主機運行JavaScript,並將我的主頁也設置在Google應用程序註冊到本地主機。

任何幫助將非常感激。

代碼:

<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> 

回答

2

我搜索了同樣的錯誤起源不匹配today.after位我得到的原因。

在創建谷歌API訪問,我們必須指定授權的重定向URI授權的重定向URI

現在,如果你調用從比授權的重定向URI指定其他的URI的登錄,error:Unknown Origin is thrown

FYI:我看到你正在運行的JavaScript本地使用本地主機。 這意味着您沒有將本地主機URI添加到授權重定向URI。

但是不要浪費你的時間來做這件事。授權重定向URIs不會接受本地主機URI。這是由於Chrome的同源策略。如果你使用disable-web-security標誌運行chrome,它將在本地工作太。

+0

聽起來很合理,但... '''cd「/ Applications/Google Chrome Canary.app/Contents/MacOS/」''' - >'''./Google \ Chrome \ Canary --disable- web-security''' - >'''Trace/BPT陷阱:5''' - >'''Google Chrome意外退出.''' –

+0

在Firefox中運行...正常工作 –

+0

@CraigMorgan:chrome FF中的擴展? –

1

起源錯配的問題可以通過在谷歌開發者控制檯創建客戶端ID時照顧了重定向的URIJavaScript來源來解決。

JavaScript源應該結束與/

示例http://example.com/ - >正確的格式將是http://example.com