Search code examples
javascriptgoogle-contacts-api

No 'Access-Control-Allow-Origin' header is present on the requested resource. (google contacts api)


I am trying to get photo of google contact. from api guide found this:

https://www.google.com/m8/feeds/photos/media/{userEmail}/{contactId}

my code:

`$.get("https://www.google.com/m8/feeds/photos/media/default/54b8abe0f52ad02?access_token=" + authorizationResult.access_token + "&v=3.0",
        function(response){
          //process the response here
          console.log(response);
        }
      );`

it gives me this error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

but this seems to be working fine

`$.get("https://www.google.com/m8/feeds/contacts/default/full?alt=json&access_token=" + authorizationResult.access_token + "&max-results=500&v=3.0",
        function(response){
          //process the response here
          console.log(response);
        }
      );`

Edit: full js script:

`

<script type="text/javascript">
  var clientId = 'my client id';
  var apiKey = 'api key';
  var scopes = 'https://www.googleapis.com/auth/contacts.readonly';
  $(document).on("click",".googleContactsButton", function(){
    gapi.client.setApiKey(apiKey);
    window.setTimeout(authorize);
  });
  function authorize() {
    gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization);
  }
  function handleAuthorization(authorizationResult) {
    if (authorizationResult && !authorizationResult.error) {
      $.get("https://www.google.com/m8/feeds/photos/media/default/54b8abe0f52ad02?access_token=" + authorizationResult.access_token + "&v=3.0",
        function(response){
          //process the response here
          console.log(response);
        }
      );
    }
  }
</script>

`


Solution

  • I got the picture by doing this: (prefix image url with proxy url)

    `  function handleAuthorization(authorizationResult) {
        if (authorizationResult && !authorizationResult.error) {
          console.log(authorizationResult);
          var accessToken = authorizationResult.access_token;
          $.get("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + accessToken + "&max-results=500&v=3.0",
            function(response){
              //process the response here
              console.log(response);
              let photoUrl = response.feed.entry[2].link[0].href + "&access_token=" + accessToken;
              let proxy = 'https://cors.now.sh/';
              let finalPhotoUrl = proxy + photoUrl;
              document.getElementById('photo').src = finalPhotoUrl;
            }
          );
        }
      }`