首页 > 解决方案 > “无法设置未定义的属性‘jwtClient’”尝试将 Node.js 与 Google 表格一起使用

问题描述

我一直在关注本教程:https ://www.youtube.com/watch?v= UGN6EUi4Yio 由于这个问题,我不得不在 3:43 停下来:

这是进入 Google 电子表格的主要 JS 文件:

const GoogleSpreadsheet = require('google-spreadsheet');
const { promisify } = require('util');
const { google } = require('googleapis');


const creds = require('./client_secret');

async function accessSpreadsheet()
{
    const doc = new GoogleSpreadsheet.GoogleSpreadsheet('1i1uSTZ5GkMJFqUGpxsvCOIOZJ6POPOuS9Vu0kDP1y_w');

    await promisify(doc.useServiceAccountAuth)(creds);
    const info = await promisify(doc.getInfo)();
    const sheet = info.worksheets[0];
    console.log(`TItle : ${sheet.title}, Rows: ${sheet.rowCount}`);
}

accessSpreadsheet();

当我执行这个时,它给了我这个错误:

TypeError: Cannot set property 'jwtClient' of undefined
at useServiceAccountAuth (C:\Users\Web\WebstormProjects\discordjs\node_modules\google-spreadsheet\lib\GoogleSpreadsheet.js:53:20)"

所以我去探索寻找功能。这是 GoogleSpreadsheet.js,在此代码块末尾带有预期的功能(删除了该类的其余部分):

const _ = require('lodash');
const { JWT } = require('google-auth-library');
const Axios = require('axios');

const GoogleSpreadsheetWorksheet = require('./GoogleSpreadsheetWorksheet');
const { getFieldMask } = require('./utils');

const GOOGLE_AUTH_SCOPES = [
  'https://www.googleapis.com/auth/spreadsheets',

  // the list from the sheets v4 auth for spreadsheets.get
  // 'https://www.googleapis.com/auth/drive',
  // 'https://www.googleapis.com/auth/drive.readonly',
  // 'https://www.googleapis.com/auth/drive.file',
  // 'https://www.googleapis.com/auth/spreadsheets',
  // 'https://www.googleapis.com/auth/spreadsheets.readonly',
];

const AUTH_MODES = {
  JWT: 'JWT',
  API_KEY: 'API_KEY',
};

class GoogleSpreadsheet {
  constructor(sheetId) {
    this.spreadsheetId = sheetId;
    this.authMode = null;
    this._rawSheets = {};
    this._rawProperties = null;

    // create an axios instance with sheet root URL and interceptors to handle auth
    this.axios = Axios.create({
      baseURL: `https://sheets.googleapis.com/v4/spreadsheets/${sheetId}`,
    });
    // have to use bind here or the functions dont have access to `this` :(
    this.axios.interceptors.request.use(this._setAxiosRequestAuth.bind(this));
    this.axios.interceptors.response.use(
      this._handleAxiosResponse.bind(this),
      this._handleAxiosErrors.bind(this)
    );

    return this;
  }

  // AUTH RELATED FUNCTIONS ////////////////////////////////////////////////////////////////////////
  async useApiKey(key) {
    this.authMode = AUTH_MODES.API_KEY;
    this.apiKey = key;
  }

  // creds should be an object obtained by loading the json file google gives you
  async useServiceAccountAuth(creds) {
    this.jwtClient = new JWT({
      email: creds.client_email,
      key: creds.private_key,
      scopes: GOOGLE_AUTH_SCOPES,
    });
    await this.renewJwtAuth();
  }

creds 文件信息(参数)似乎使用 console.log 输出良好。

我是 JavaScript 的初学者,并且已经阅读了如何初始化这些属性,但没有运气。GoogleSpreadsheet.js 不是我的代码。

标签: javascriptnode.jsgoogle-apps-scriptgoogle-sheets

解决方案


似乎 node_module 'google-spreadsheets' 已经发布了一个新版本。

通过这个模块文档的混搭和来自 Twilio 的视频,我能够克服上述错误。

const { GoogleSpreadsheet } = require('google-spreadsheet');
const creds = require('./credentials.json');

// spreadsheet key is the long id in the sheets URL
const doc = new GoogleSpreadsheet('1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms');

async function accessSpreadsheet() {
  await doc.useServiceAccountAuth({
    client_email: creds.client_email,
    private_key: creds.private_key,
  });

  await doc.loadInfo(); // loads document properties and worksheets
  console.log(doc.title);

  const sheet = doc.sheetsByIndex[0]; // or use doc.sheetsById[id]
  console.log(sheet.title);
  console.log(sheet.rowCount);

}

accessSpreadsheet();

推荐阅读