“GAPI 未定义”消息

2024-01-30

我正在尝试使用 Google Sheets API 包含在我的网络应用程序中,但我不断收到一条错误,指出未定义igapi 库。我尝试使用 ComponentDidMount 生命周期方法延迟对服务器的请求,甚至在该方法中使用超时,但我不断收到相同的错误。我怎样才能定义gapi库以便在我的应用程序中使用?

import React from 'react';
var CLIENT_ID = ''; 
var SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"];


export default class MyNavbar extends React.Component {

  constructor(props) {
    super(props);
  }

  componentDidMount(){
     this.checkAuth();

   }

      /**
       * Check if current user has authorized this application.
       */      
    checkAuth(){
        gapi.auth.authorize(
          {
            'client_id': CLIENT_ID,
            'scope': SCOPES.join(' '),
            'immediate': true
          }, this.handleAuthResult());
      }

      /**
       * Handle response from authorization server.
       *
       * @param {Object} authResult Authorization result.
       */
      handleAuthResult(authResult) {
        var authorizeDiv = document.getElementById('authorize-div');
        if (authResult && !authResult.error) {
          // Hide auth UI, then load client library.
          authorizeDiv.style.display = 'none';
          loadSheetsApi();
        } else {
          // Show auth UI, allowing the user to initiate authorization by
          // clicking authorize button.
          authorizeDiv.style.display = 'inline';
        }
      }

      /**
       * Initiate auth flow in response to user clicking authorize button.
       *
       * @param {Event} event Button click event.
       */
     handleAuthClick(event) {
        gapi.auth.authorize(
          {client_id: CLIENT_ID, scope: SCOPES, immediate: false},
          handleAuthResult);
        return false;
      }

      /**
       * Load Sheets API client library.
       */
     loadSheetsApi() {
        var discoveryUrl =
            'https://sheets.googleapis.com/$discovery/rest?version=v4';
        gapi.client.load(discoveryUrl).then(listMajors);
      }

      /**
       * Print the names and majors of students in a sample spreadsheet:
       * https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
       */
      listMajors() {
        gapi.client.sheets.spreadsheets.values.get({
          spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
          range: 'Class Data!A2:E',
        }).then(function(response) {
          var range = response.result;
          if (range.values.length > 0) {
            appendPre('Name, Major:');
            for (i = 0; i < range.values.length; i++) {
              var row = range.values[i];
              // Print columns A and E, which correspond to indices 0 and 4.
              appendPre(row[0] + ', ' + row[4]);
            }
          } else {
            appendPre('No data found.');
          }
        }, function(response) {
          appendPre('Error: ' + response.result.error.message);
        });
      }

      /**
       * Append a pre element to the body containing the given message
       * as its text node.
       *
       * @param {string} message Text to be placed in pre element.
       */
      appendPre(message) {
        var pre = document.getElementById('output');
        var textContent = document.createTextNode(message + '\n');
        pre.appendChild(textContent);
      }


   render(){
      return (
        <div>
          <h1>Hello World My Name Is Justin 2</h1>
          <div id="authorize-div"></div>
          <pre id="output"></pre>   
        </div>
      );
    }
}

在这里试试这个。

import React from 'react';
import asyncLoad from 'react-async-loader'; // for loading script tag asyncly `npm i --save react-async-loader`

const CLIENT_ID = '';
const SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"];

// For making gapi object passed as props to our component
const mapScriptToProps = state => ({
   // gapi will be this.props.gapi
   gapi: {
      globalPath: 'gapi',
      url: 'https://your-gapi-url'
   }
});

@asyncLoad(mapScriptToProps)
class MyNavbar extends React.Component {

  constructor(props) {
    super(props);
    this.gapi = null;
    // You need to bind methods to this class's object context. (i.e this)!
    this.checkAuth = this.checkAuth.bind(this);
    this.handleAuthResult = this.authResult.bind(this);
    this.handleAuthClick = this.handleAuthClick.bind(this);
    this.loadSheetsApi = this.loadSheetsApi.bind(this);
    this.listMajors = this.listMajors.bind(this);
  }

  componentDidMount() {
    // Check is gapi loaded?
    if (this.props.gapi !== null) {
       this.checkAuth();
    }
  }

  componentWillReceiveProps({ gapi }) {
    if (gapi!== null) {
      this.checkAuth();
    }
  }

   /**
   * Check if current user has authorized this application.
   */
  checkAuth() {

    // this will give you an error of gapi is not defined because there is no
    // reference of gapi found globally you cannot access global object which are
    // not predefined in javascript( in this case its window.gapi ).
    // properties added by Programmer cannot be accessed directly( if it's not in the same file as well as the same scope!) in commonjs modules. Because they
    // don't' run in a global scope. Any variable in another module which is not
    // exported, will not be available to other modules.

    this.gapi = window.gapi; // you can do like this. Now you can access gapi in all methods if this class.
    this
        .gapi
        .auth
        .authorize({
            'client_id': CLIENT_ID,
            'scope': SCOPES.join(' '),
            'immediate': true
        }, this.handleAuthResult());
  }

   /**
   * Handle response from authorization server.
   *
   * @param {Object} authResult Authorization result.
   */
  handleAuthResult(authResult) {
    var authorizeDiv = document.getElementById('authorize-div');
    if (authResult && !authResult.error) {
        // Hide auth UI, then load client library.
        authorizeDiv.style.display = 'none';
        loadSheetsApi();
    } else {
        // Show auth UI, allowing the user to initiate authorization by clicking
        // authorize button.
        authorizeDiv.style.display = 'inline';
    }
  }

  /**
   * Initiate auth flow in response to user clicking authorize button.
   *
   * @param {Event} event Button click event.
   */
  handleAuthClick(event) {
    // gapi.auth.authorize(  here also gapi is not defined  
     this
        .gapi
        .auth
        .authorize({
            client_id: CLIENT_ID,
            scope: SCOPES,
            immediate: false
        }, handleAuthResult);
    return false;
  }

  /**
   * Load Sheets API client library.
   */
  loadSheetsApi() {
    var discoveryUrl = 'https://sheets.googleapis.com/$discovery/rest?version=v4';
    // also will give your error
    // for gapi being not defined.
    // gapi.client.load(discoveryUrl).then(listMajors); 
    this
        .gapi
        .client
        .load(discoveryUrl)
        .then(listMajors);
  }

  /**
   * Print the names and majors of students in a sample spreadsheet:
   * https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
   */
  listMajors() {
    this.gapi
        .client
        .sheets
        .spreadsheets
        .values
        .get({spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms', range: 'Class Data!A2:E'})
        .then(function (response) {
            var range = response.result;
            if (range.values.length > 0) {
                appendPre('Name, Major:');
                for (i = 0; i < range.values.length; i++) {
                    var row = range.values[i];
                    // Print columns A and E, which correspond to indices 0 and 4.
                    appendPre(row[0] + ', ' + row[4]);
                }
            } else {
                appendPre('No data found.');
            }
        }, function (response) {
            appendPre('Error: ' + response.result.error.message);
        });
  }

 /**
   * Append a pre element to the body containing the given message
   * as its text node.
   *
   * @param {string} message Text to be placed in pre element.
   */
  appendPre(message) {
    // as you can see. You are accessing window.document as document. 
    // its fine because its defined in javascript (implicitly),
    // not explicitly by programmer(here you!).
    var pre = document.getElementById('output'); 
    var textContent = document.createTextNode(message + '\n');
    pre.appendChild(textContent);
  }

  render() {
    return (
        <div>
            <h1>Hello World My Name Is Justin 2</h1>
            <div id="authorize-div"></div>
            <pre id="output"></pre>
        </div>
    );
  }
}

export default MyNavbar;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

“GAPI 未定义”消息 的相关文章

随机推荐

  • jQueryeach() 闭包 - 如何访问外部变量

    从 each 中访问 this rules 变量的最佳方法是什么 任何关于原因 方式的解释也会有帮助 app Style function node this style node this rules var ruleHolder nod
  • 为什么perl配置VC-WIN64A后没有ms\do_ms.bat?

    我正在使用 Visual Studio 2015 编译 OpenSSL 我已经安装了 Windows 10 上的 Visual Studio 2015 ActivePerl 5 24 0 2400 MSWin32 x64 300558 na
  • 如何在不使用非 api 类的情况下取消 Java 中的 Files.copy() ?

    我正在下载一个文件Files copy method Files copy in Paths get targetZipFile StandardCopyOption REPLACE EXISTING 如果下载很慢我想取消它 我在 stac
  • gcov 在当前目录中创建 .gcov 文件。有什么办法可以改变这个吗?

    我在 RHEL 上运行 gcov gcc 4 1 2 当我想为 gcov 文件指定目录时 关于如何做到这一点有什么想法吗 从您想要创建其文件的目录运行 gcov 你必须使用 o参数告诉它在哪里查找 gcno gcda 文件 看gcov 的文
  • 是什么让 SPI 比 I2C 协议更快 [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我了解 I2C 和 SPI 通信的基础知识 因为两者都是同步协议 我想知道是什么让 SPI 比 I2C 更快 如果我没记错的话 使用 I2
  • Docker:理解ENTRYPOINT和CMD指令

    我想问一些关于ENTRYPOINT and CMD可在 Dockerfile 中使用的说明 Providing that I m mounting local directories as volumes in a container us
  • 如何检查我当前是否在主屏幕上

    是否可以检查我的应用程序当前是否处于后台并且主屏幕是否已启动 没有 API 可以知道主屏幕是否正在显示 但是 您可以使用各种 Activity 生命周期回调 onStop 等 知道您的应用程序何时发送到后台
  • 为什么未装箱的数组不是可折叠的实例?

    在 Haskell 中找出要使用的正确数据容器可能有点棘手 对于我认为使用的 2D 网格应用程序UArray会是合适的 然而 据我所知UArray不是一个实例foldable 不在Data Array IArray nor Data Arr
  • Flutter SQFlite 一对多关系设置

    我正在创建一个应用程序并需要一个数据库 该数据库包含位置表和兴趣点表 这是一对多的关系 一个位置有多个兴趣点 现在我尝试用 sqflite 在 flutter 中建立这种关系 但失败了 我已经尝试添加外键 但没有成功 这只是代码中最重要的部
  • RecyclerView ViewHolder 内部 ConstraintLayout 的性能

    在过去的两天里 我一直在尝试分类为什么我的 RecyclerView 在滚动时速度如此之慢 并且我已将其范围缩小到我用于行的 ConstraintLayout 在 Android 上使用 GPU 分析器会显示绿色 蓝绿色条一直到屏幕顶部 表
  • 使用 XmlSlurper 解析(非常)大的 XML 文件

    我对 Groovy 有点陌生 我正在尝试使用 XmlSlurper 读取一个 相当 大的 XML 文件 超过 1Gb 由于它不构建整个 DOM 因此它应该能够在处理大文件时产生奇迹 在记忆中 尽管如此 我还是不断收到 OutOfMemory
  • 在 PL/pgSQL 函数中拆分逗号分隔的字符串

    我正在尝试编写一个函数 该函数将 ID 作为输入并更新该给定 ID 上的一些字段 到目前为止 它看起来像这样 CREATE FUNCTION update status p id character varying p status cha
  • 如何在 Laravel 中解密哈希密码

    我用谷歌搜索了很多 但不幸的是没有找到有效的解决方案 我知道这是一种糟糕的技术 但我需要通过电子邮件向用户发送密码 我已设法发送用户哈希密码 但我无法解密该密码 以下是我正在使用的程序 results DB select select fr
  • 将 postgreSQL 存储过程作为一个事务执行

    我正在使用 PostgreSQL 9 3 并且创建了一些包含多个语句的存储过程 我在准备好的语句的帮助下在 Java 应用程序中调用此存储过程 现在我读到存储过程中的每个语句都作为一个事务执行 即每个语句后一次提交 但我想要的是将整个存储过
  • nginx WordPress URL 重写

    我刚刚安装了 nginx 1 0 8 和 php fpm 在过去 30 分钟里我试图重写 WordPress 的 URL WordPress URL 应如下所示 http localhost website blog 2011 10 sam
  • 在 OSX 上,Valgrind 报告此内存泄漏,它来自哪里?

    在 OSX 上 Valgrind 报告此内存泄漏 它来自哪里 该代码是用 g 作为 c 代码编译的 我这样做是为了函数重载 13088 18 bytes in 1 blocks are definitely lost in loss rec
  • 通过管道输入到脚本,然后从用户获取输入

    假设我想将输入通过管道传输到 Python 程序 然后在命令行上从用户那里获取输入 echo http example com image jpg python solve captcha py 和内容solve captcha py ar
  • 如何在纸张输入中添加所需的指示器

    给定纸张输入
  • Flash CS4 + SQLITE

    我正在寻找一些有关在 Flash CS4 中使用 SQLITE 和 AIR 的信息 我找不到任何好的示例 它们都是为 Flex 构建的 我不想使用它 谁能给我一些如何使用 Flash CS4 执行此操作的基本示例 或者指导我一些代码示例 教
  • “GAPI 未定义”消息

    我正在尝试使用 Google Sheets API 包含在我的网络应用程序中 但我不断收到一条错误 指出未定义igapi 库 我尝试使用 ComponentDidMount 生命周期方法延迟对服务器的请求 甚至在该方法中使用超时 但我不断收