首页 > 解决方案 > Google API 演示在本地无法运行;GAPI 为空

问题描述

我从本教程中复制了 Google 的演示代码: https ://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get

但是,当我尝试在本地运行它时,出现以下错误。

testoJS.html:14 Uncaught TypeError: Cannot read property 'signIn' of null
at authenticate

gapi即使代码预先导入了 api 模块,我也不确定为什么变量为空。

这是我的代码的副本;我的客户端 ID、API 密钥和电子表格 ID 是正确的 - 我在上述网站的“试用此 API”部分中测试了这些值。http 请求在那里工作得很好,并返回电子表格的内容。但是,我似乎无法在本地运行它。

<html>
  <head></head>
  <body>
   <script src="https://apis.google.com/js/api.js"></script>
    <script>
      /**
       * Sample JavaScript code for sheets.spreadsheets.values.get
       * 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/drive https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/spreadsheets.readonly"})
            .then(function() { console.log("Sign-in successful"); },
                  function(err) { console.error("Error signing in", err); });
      }
      function loadClient() {
        gapi.client.setApiKey("API_KEY");
        return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/sheets/v4/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.sheets.spreadsheets.values.get({
          "spreadsheetId": "SPREADSHEETID",
          "range": "A1:D4"
        })
            .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: "CLIENT_ID"});
      });
    </script>
    <button onclick="authenticate().then(loadClient)">authorize and load</button>
    <button onclick="execute()">execute</button>
  </body>
</html>

标签: javascriptgoogle-sheetsgoogle-apirequestclient

解决方案


推荐阅读