使用Google Cloud Service帐户访问私人Google表
我有一个私有的 Google 电子表格,我正在尝试使用 Google Visualization/Google Charts 以编程方式访问它。我已经创建了服务帐户,并尝试使用 google-auth-library
和 googleapis
npm 包来创建一个访问令牌,然后我可以用它来访问电子表格。但是,当我尝试使用该访问令牌从电子表格中读取时,请求失败并显示 HTTP 代码 401(未经授权)。我需要做什么才能使这项工作成功?
这是我的代码:
const { auth } = require('google-auth-library');
const keys = require('./jwt.keys.json');
const id = '{Spreadsheet ID}';
const sheetId = '{Sheet ID}';
const query = "{Query}";
async function getClient(){
const client = auth.fromJSON(keys);
client.scopes = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
console.log(client);
return client;
}
async function main(){
const client = await getClient();
const token = await client.getAccessToken();
console.log(token);
console.log(token.token);
const url = `https://docs.google.com/spreadsheets/d/${id}/gviz/tq?tqx=out:csv&tq=${encodeURIComponent(query)}&access_token=${token.token}#gid=${sheetId}`;
const res = await client.request({url});
console.log(res);
}
main().catch(console.error);
I have a private Google Spreadsheet and I’m trying to access it programmatically using Google Visualization/Google Charts. I've created the service account, and I have tried using the google-auth-library
and googleapis
npm packages to create an access token that I can then use to access the spreadsheet. But, when I try to use that access token to read from the spreadsheet, the request fails with HTTP code 401 (Unauthorized). What do I need to do in order to make this work?
This is my code:
const { auth } = require('google-auth-library');
const keys = require('./jwt.keys.json');
const id = '{Spreadsheet ID}';
const sheetId = '{Sheet ID}';
const query = "{Query}";
async function getClient(){
const client = auth.fromJSON(keys);
client.scopes = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
console.log(client);
return client;
}
async function main(){
const client = await getClient();
const token = await client.getAccessToken();
console.log(token);
console.log(token.token);
const url = `https://docs.google.com/spreadsheets/d/${id}/gviz/tq?tqx=out:csv&tq=${encodeURIComponent(query)}&access_token=${token.token}#gid=${sheetId}`;
const res = await client.request({url});
console.log(res);
}
main().catch(console.error);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当我看到你的脚本时,我认为需要修改范围。我遇到了与您相同的情况(使用您的端点的状态代码
401
)。不幸的是,您的端点似乎无法在https://www.googleapis.com/auth/spreadsheets.readonly
范围内使用。那么,例如,按如下方式进行更改,然后再次测试如何?发件人:
收件人:
或
注意:
When I saw your script, I thought that it is required modifying the scope. I had got the same situation as you (the status code
401
using your endpoint). Unfortunately, it seems that your endpoint cannot be used using the scope ofhttps://www.googleapis.com/auth/spreadsheets.readonly
. So, for example, how about changing it as follows, and testing it again?From:
To:
or
Note: