提问者:小点点

“无法访问属性”GetAuthInstance“,Gapi.Auth2未定义”尝试使用YouTube数据API时出错


所以我对API和类似的东西还是个新手。 最近,我接到了一个任务,要列出一个特定Youtube频道的视频。 所以我得到的变通方法是首先收集uploads播放列表的id,然后从该播放列表中获取所有视频以显示它们。 但事情是,我不能走得这么远,我首先从Googles API文档中获得代码,做了一些编辑(我的API键和类似的东西),当我运行时,我得到了这个错误:

未捕获的TypeError:无法访问属性“GetAuthInstance”,Gapi.Auth2未定义

下面是我正在使用的代码(我将删除我的API键,所以不要认为这是错误):

null

<script src="https://apis.google.com/js/api.js"></script>
  <script>
    /**
     * Sample JavaScript code for youtube.channels.list
     * See instructions for running APIs Explorer code samples locally:
     * https://developers.google.com/explorer-help/guides/code_samples#javascript
     */

    function authenticate() {
      return gapi.auth2.getAuthInstance()
        .signIn({
          scope: "https://www.googleapis.com/auth/youtube.readonly"
        })
        .then(function() {
            console.log("Sign-in successful");
          },
          function(err) {
            console.error("Error signing in", err);
          });
    }

    function loadClient() {
      gapi.client.setApiKey("my API key was here");
      return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
        .then(function() {
            console.log("GAPI client loaded for API");
          },
          function(err) {
            console.error("Error loading GAPI client for API", err);
          });
    }
    // Make sure the client is loaded and sign-in is complete before calling this method.
    function execute() {
      return gapi.client.youtube.channels.list({
          "part": [
            "contentDetails"
          ],
          "id": [
            "My Channel ID was here"
          ]
        })
        .then(function(response) {
            // Handle the results here (response.result has the parsed body).
            console.log("Response", response);
          },
          function(err) {
            console.error("Execute error", err);
          });
    }
    /*gapi.load("client:auth2", function() {
      gapi.auth2.init({
        client_id: "YOUR_CLIENT_ID"
      });
    });*/
  </script>
  <button onclick="authenticate().then(loadClient)">authorize and load</button>
  <button onclick="execute()">execute</button>

null

从错误的外观上看,我认为api.js库有问题,或者在调用GetAuthInstance之前,可能需要执行另一个函数。 我不知道发生了什么事,希望有人能给我解释一下,谢谢


共1个答案

匿名用户

我自己对这些东西了解不多,所以我在文档中找到了以下部分:https://developers.google.com/identity/sign-in/web/reference#GAPIAuth2GetAuthInstance

结果表明,您需要首先初始化auth--您在代码底部注释掉的部分:

/*gapi.load("client:auth2", function() {
  gapi.auth2.init({
    client_id: "YOUR_CLIENT_ID"
  });
});*/

测试一下,看看你得到了什么:D