3

I am trying to access data from google contacts api using cors.

i can do this on the o auth 2.0 playground but when i try and do it from my app it gives the follwoing error messages in the console of google chrome.

405 method not allowed and No 'Access-Control-Allow-Origin' header is present on the requested resource.

here is my code:

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

as far as i can tell i have done this as documented in the google documentation for making cors requests using javascript.

there code from "How to use CORS to access Google APIs" page:

 {
  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();
 }
Tony Cronin
  • 1,623
  • 1
  • 24
  • 30
user2897377
  • 163
  • 1
  • 9

1 Answers1

0

Not enough points to comment yet, hence I post an answer.

The issue seems to be that the Google server does not properly handle CORS, and you can only use JSONP to retrieve information, cf. this similar issue and answer. In short, the domain shared contacts API handles access-control-allow-origin correctly only for JSONP GETs.

Community
  • 1
  • 1