登录后 YouTube API 请求不起作用
YouTube API request not working when I'm logged in
我正在使用 Yeoman 的 angular-fullstack 生成器进行登录和身份验证。
当我注释掉身份验证代码并发出 YouTube API 请求时,它运行良好。但是当我取消注释验证码、登录并发出相同的 YouTube API 请求时,它不起作用。
这是正在发生的事情:
它以某种方式向 videos?part=...
发出相同的 API 请求两次。当我没有登录时,它只会发生一次。
所以第一个成功了:
但是第二个不成功:
我有两个问题:
1) 为什么会生成第二个 HTTP 请求?
这是用于发出请求的代码的摘录:
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" 只记录一次,我不知道是什么生成了第二个 HTTP 请求。
2) 为什么第二次HTTP请求不成功?请求之间的唯一区别似乎是授权 header。我对此了解不多,但它似乎是一个 request with credentials,据我了解,响应具有 access-control-allow-credentials: true
的事实应该使这项工作成为可能。
我不确定我应该 post 什么代码,所以 here 是 GitHub 上的所有代码。
编辑:这是我注释掉授权码后成功请求的样子。
第一个请求是 "preflight request":OPTION
请求以确保远程服务器允许您发出真正的请求(浏览器需要 access-control-allow-origin
)。你只在尝试记录查询时才拥有它似乎很奇怪,但这可能是 access-control-max-age
的副作用:此预检请求的缓存持续时间。
第二个请求才是真正的POST
。 Google documentation 表示:
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.
您应该检查 "Calling the YouTube Data API" 部分以查看您的令牌是否有效以及 sample request 是否有效。
关于 access-control-allow-credentials
:默认行为是 不 发送任何 cookie(没有这个 header 就不会),您可以发送它们$http.get('...', {withCredentials: true})
.
我正在使用 Yeoman 的 angular-fullstack 生成器进行登录和身份验证。
当我注释掉身份验证代码并发出 YouTube API 请求时,它运行良好。但是当我取消注释验证码、登录并发出相同的 YouTube API 请求时,它不起作用。
这是正在发生的事情:
它以某种方式向 videos?part=...
发出相同的 API 请求两次。当我没有登录时,它只会发生一次。
所以第一个成功了:
但是第二个不成功:
我有两个问题:
1) 为什么会生成第二个 HTTP 请求?
这是用于发出请求的代码的摘录:
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" 只记录一次,我不知道是什么生成了第二个 HTTP 请求。
2) 为什么第二次HTTP请求不成功?请求之间的唯一区别似乎是授权 header。我对此了解不多,但它似乎是一个 request with credentials,据我了解,响应具有 access-control-allow-credentials: true
的事实应该使这项工作成为可能。
我不确定我应该 post 什么代码,所以 here 是 GitHub 上的所有代码。
编辑:这是我注释掉授权码后成功请求的样子。
第一个请求是 "preflight request":OPTION
请求以确保远程服务器允许您发出真正的请求(浏览器需要 access-control-allow-origin
)。你只在尝试记录查询时才拥有它似乎很奇怪,但这可能是 access-control-max-age
的副作用:此预检请求的缓存持续时间。
第二个请求才是真正的POST
。 Google documentation 表示:
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.
您应该检查 "Calling the YouTube Data API" 部分以查看您的令牌是否有效以及 sample request 是否有效。
关于 access-control-allow-credentials
:默认行为是 不 发送任何 cookie(没有这个 header 就不会),您可以发送它们$http.get('...', {withCredentials: true})
.