Search code examples
angularjshttpyoutube-apicorsyeoman-generator

YouTube API request not working when I'm logged in


I'm using Yeoman's angular-fullstack generator to do login and authentication.

When I comment out the code for authentication and make YouTube API requests, it works perfectly. But when I uncomment the authentication code, log in, and make the same YouTube API request, it doesn't work.

Here's what's happening:

enter image description here

Somehow it's making the same API request (to videos?part=...) twice. When I'm not logged in it only happens once.

So the first one is successful:

enter image description here

But the second one is unsuccessful:

enter image description here

I have two questions:

1) Why is a second HTTP request being generated?

Here is an excerpt of the code used to make the request:

console.log('before request');
$http.get('https://www.googleapis.com/youtube/v3/videos?part=snippet%2C+contentDetails&id='+videoId+'&key='+API_KEY)
  .success(function(result) {
    console.log('success');
    var item = result.items[0];
    vm.skim.title = item.snippet.title;
    vm.skim.description = item.snippet.description;

"before request" only gets logged once, and I can't figure out what is generating the second HTTP request.

2) Why is the second HTTP request unsuccessful? The only difference between the requests seems to be that Authorization header. I don't know much about this, but it seems to be a request with credentials, and from what I understand, the fact that the response has access-control-allow-credentials: true should make this work.

I'm not sure what code I should post, so here is all of it on GitHub.

Edit: Here is what a successful request looks like when I comment out the authorization code.

enter image description here


Solution

  • The first request is a "preflight request" : an OPTION request to make sure that the remote server allows you to make the real request (the browser expects a access-control-allow-origin). It seems strange that you only have it when trying a logged query, but that may be a side effect of access-control-max-age : that the cache duration of this preflight request.

    The second request is the real POST. The Google documentation says :

    The API returns an HTTP 401 response code (Unauthorized) if you submit a request to access a protected resource with an access token that is expired, bogus, improperly scoped, or invalid for some other reason.

    You should check the "Calling the YouTube Data API" part to see if your token is valid and if a sample request works.

    About the access-control-allow-credentials : the default behavior is to not send any cookie (and won't without this header), you can send them with $http.get('...', {withCredentials: true}).