【问题标题】:Youtube API query returns nullYoutube API 查询返回 null
【发布时间】:2014-01-18 19:13:19
【问题描述】:

“Kanye West Amazing”的 youtube 搜索查询应返回多个 youtube 链接。但是,通过 api 的 youtube 查询返回 null(来自 console.log):

<!doctype html>
<html>
  <head>
    <title>Vidify</title>
  </head>

  <body>
    <!--Add a button for the user to click to initiate auth sequence -->
    <button id="authorize-button" style="visibility: hidden">Authorize</button>
    <script type="text/javascript">

      var clientId = '591751286145-ktngvf2s76uiuuevan6mo1fft0kchl8l.apps.googleusercontent.com';

      var apiKey = 'AIzaSyB0mteDV5vDKFR-iAv4Fx4OC2gp1Yhqe9U';

      var scopes = 'https://www.googleapis.com/auth/youtube';

      function handleClientLoad() {
        console.log('API key provided - authorizing client...');
        // Step 2: Reference the API key
        gapi.client.setApiKey(apiKey);
        gapi.auth.init(checkAuth);
      }

      function checkAuth() {
        console.log('entered checkAuth - authorizing...');
        setTimeout(function() { 
            console.log("requesting auth");
            gapi.auth.authorize({ 
                client_id: clientId, 
                scope: scopes, 
                response_type:'token',
                immediate: true 
            }, handleAuthResult); 
        }, 100); 
      }

      function handleAuthResult(authResult) {
        console.log('received authResult');
        var authorizeButton = document.getElementById('authorize-button');
        if (authResult && !authResult.error) {
          console.log("auth. successful");
          authorizeButton.style.visibility = 'hidden';
          makeApiCall();
        } else {
          console.log('auth failed.');
          authorizeButton.style.visibility = '';
          authorizeButton.onclick = handleAuthClick;
        }
      }

      function handleAuthClick(event) {
        // Step 3: get authorization to use private data
        console.log('retry');
        gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
        return false;

      }

      // Load the API and make an API call.  Display the results on the screen.
        function makeApiCall() {
            console.log("loaded client");
            gapi.client.setApiKey(apiKey);
            // Step 4: Load the Google+ API
            gapi.client.load('youtube', 'v3', function() {
                console.log('youtube API loaded...');
                // Step 5: Assemble the API request
                var qVar = "Kanye West Amazing"
                // changed. added: type
                var request = gapi.client.youtube.search.list({
                    type: 'video',
                    part: 'id',
                    q: qVar
                });
                // Step 6: Execute the API request
                request.execute(function(resp) {

                    console.log(resp);
                    var vid = document.createElement('vid');
                    vid.value = resp.items[0].id.videoId;
                    console.log(vid.value);
                    var youtube_url = "http://www.youtube.com/watch?v=";
                    youtube_url += vid.value;
                    youtube_url += "&rel=0";
                    window.open(youtube_url);
                });
              });
          }
    </script>

    <script src="https://apis.google.com/js/client.js?onload=makeApiCall"></script>

  </body>
</html>

所以我实际上是在尝试从 spotify 桌面应用程序中运行它。 spotify 应用程序系统允许我从“spotify 浏览器”中加载 index.html。以下是我现在遇到的错误:

未捕获的类型错误:无法调用未定义的方法“setApiKey”

index.html:63 makeApiCall index.html:63(匿名函数)

client.js?onload=makeApiCall:6 fa client.js?onload=makeApiCall:1 b

client.js?onload=makeApiCall:6 v.(匿名函数)

client.js?onload=makeApiCall:6 H.(匿名函数)

client.js?onload=makeApiCall:6(匿名函数)cb=gapi.loaded_0:1

未捕获的类型错误:无法读取未定义的属性“原型” cb=gapi.loaded_0:6

_.J cb=gapi.loaded_0:6(匿名函数)cb=gapi.loaded_1:6(匿名函数)client.js?onload=makeApiCall:4 Z

client.js?onload=makeApiCall:6 ua client.js?onload=makeApiCall:4 E

client.js?onload=makeApiCall:5 b client.js?onload=makeApiCall:6

v.(匿名函数) client.js?onload=makeApiCall:6 H.(匿名 函数)client.js?onload=makeApiCall:6(匿名函数) cb=gapi.loaded_1:1

【问题讨论】:

    标签: javascript youtube youtube-api google-api google-api-client


    【解决方案1】:

    看起来您的嵌套可能不正确;您在 gapi.client.load 函数的回调之外运行 request.execute 调用,因此在尝试运行时不会创建实际请求本身(gapi 客户端异步加载 API)。如果您尝试这样做:

      function makeApiCall() {
        // Step 4: Load the Google+ API
        gapi.client.load('youtube', 'v3', function() {
            console.log('youtube API loaded...');
            // Step 5: Assemble the API request
            var qVar = "Kanye West Amazing"
            // changed. added: type
            var request = gapi.client.youtube.search.list({
                type: 'video',
                part: 'id',
                q: qVar
            });
            // Step 6: Execute the API request
            request.execute(function(resp) {
              document.getElementById('vid').value = resp.items[1].id.videoId;
              console.log('saved video id successfully');
            });
          });
      }
    

    然后它应该等待并仅在加载 API 代码后才执行请求。当然,这也假设您有一个 id 为“vid”的元素(您的示例代码没有)。

    就范围而言,您不需要它们来进行此特定调用,因为它不需要进行身份验证(即,您可以在未经授权的情况下运行 MakeApiCall())。但是,如果您稍后要做其他需要授权的事情,它会正常运行,因此您可以轻松地将其留在里面。

    【讨论】:

    • 今晚晚些时候我会尝试进行适当的更改,并让您知道这是否有效。我确实忘记为 'vid' 制作 DOM 元素!
    • 所以在进行了这些更改之后,gapi 似乎没有加载 youtube api。更准确地说,“youtube API 已加载...”永远不会打印到控制台。在尝试加载 api 之前我还应该做些什么吗?
    • 所以换句话说,也许 makeApiCall() 不是从您的身份验证逻辑中调用的?要消除这种可能性,请尝试以下操作:在您的 makeApiCall() 函数中,定义您的 API 密钥变量(只是密钥)并进行此调用 ... gapi.client.setApiKey(apiKey); ……一开始。然后更改您的脚本元素回调以立即调用该函数(忽略身份验证内容):例行公事。
    • 所以在我意识到我的来源为空(谷歌 API 不适用于本地主机)之后,我取得了很大的进步。所以我将 index.html 添加到 xampp,现在我收到以下错误:资源解释为脚本但使用 MIME 类型文本/html 传输:“about:blank”。
    • 您是否碰巧安装了“断开连接”chrome 扩展程序(或其他隐私扩展程序)?它们有时会阻止 gapi 客户端的加载。
    猜你喜欢
    • 2019-09-20
    • 2016-12-10
    • 2019-11-02
    • 1970-01-01
    • 2016-11-07
    • 2013-12-03
    • 2013-04-28
    • 2019-06-14
    • 2020-01-07
    相关资源
    最近更新 更多