使用服务帐户文件访问 google 工作表按预期工作
import { google } from 'googleapis';
import serviceAccount from 'serviceKey.json';
const spreadsheetId = 'spreadsheet-id';
const sheets = google.sheets({ version: 'v4' });
const jwtClient = new google.auth.JWT({
email: serviceAccount.client_email,
key: serviceAccount.private_key,
scopes: ['https://www.googleapis.com/auth/spreadsheets'],
});
const appendValue = async () => {
await jwtClient.authorize();
await sheets.spreadsheets.values.append({
auth: jwtClient,
spreadsheetId,
range: 'Test!A2:E2',
valueInputOption: 'RAW',
requestBody: { values: [['A', 'B', 'C', 'D', 'E']] },
});
};
但是使用默认应用程序凭据尝试它会引发错误Login is Required。
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/serviceKey.json"
import { google } from 'googleapis';
const spreadsheetId = 'spreadsheet-id';
const sheets = google.sheets({ version: 'v4' });
const appendValue = async () => {
await sheets.spreadsheets.values.append({
spreadsheetId,
range: 'Test!A2:E2',
valueInputOption: 'RAW',
requestBody: { values: [['A', 'B', 'C', 'D', 'E']] },
});
};