![](/img/trans.png)
[英]No 'Access-Control-Allow-Origin' header is present on the requested resource. (google contacts api)
[英]trying to access google contacts api using cors getting No 'Access-Control-Allow-Origin' header is present on the requested resource
我正在嘗試使用cors從谷歌聯系人api訪問數據。
我可以在o auth 2.0操場上執行此操作,但是當我嘗試從我的應用程序執行此操作時,它會在google chrome的控制台中顯示以下錯誤消息。
不允許405方法,並且請求的資源上不存在“Access-Control-Allow-Origin”標頭。
這是我的代碼:
<button id="authorize-button" style="visibility: hidden">Authorize</button>
<script type="text/javascript">
var clientId = 'xxxxxxxx';
var apiKey = 'xxxxxxxxx';
var scopes = 'https://www.google.com/m8/feeds';
//var scopes = 'https://www.googleapis.com/auth/calendar';
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');
console.log(authResult);
if (authResult && !authResult.error)
{
authorizeButton.style.visibility = 'hidden';
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.google.com/m8/feeds/contacts/default/full");
var oauthToken = gapi.auth.getToken();
xhr.setRequestHeader('Authorization', 'Bearer ' + oauthToken.access_token);
xhr.send();
}
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>
據我所知,我已經按照google文檔中的說明使用javascript制作cors請求。
有“如何使用CORS訪問Google API”頁面中的代碼:
{
var xhr = new XMLHttpRequest();
var oauthToken = gapi.auth.getToken();
xhr.open('GET','https://www.googleapis.com/plus/v1/people/me/activities/public');
xhr.setRequestHeader('Authorization','Bearer ' + oauthToken.access_token);
xhr.send();
}
沒有足夠的評論來評論,因此我發布了答案。
問題似乎是Google服務器無法正確處理CORS,您只能使用JSONP來檢索信息,參見 這個類似的問題和答案 。 簡而言之,域共享聯系人API僅對JSONP GET正確處理access-control-allow-origin
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.