Демонстрация Google API не работает локально; GAPI равен нулю - PullRequest
0 голосов
/ 03 августа 2020

Я скопировал демонстрационный код 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 имеет значение NULL, хотя код заранее импортирует модуль api.

Вот копия моего кода; мой идентификатор клиента, ключ api и spreadsheetid верны - я проверил эти значения в разделе "Попробуйте этот 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...