【发布时间】:2020-02-22 04:24:10
【问题描述】:
我一直在关注本教程: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 不是我的代码。
【问题讨论】:
-
Sheets api 提供了很好的official tutorial。您的脚本中的问题似乎是
this是undefined- 通常在严格模式下发生,当您的函数从全局范围调用时。 this的教程 -
这条评论解决了你的问题吗?
-
@Kessy 抱歉,我刚刚才看到。是的,它有。我使用了官方文档,效果很好!谢谢!
标签: javascript node.js google-apps-script google-sheets