我有一個私人的谷歌電子表格,我正在嘗試使用谷歌可視化/谷歌圖表以編程方式訪問它。我創建了服務帳戶,并嘗試使用google-auth-library和googleapisnpm 包創建訪問令牌,然后我可以使用它來訪問電子表格。但是,當我嘗試使用該訪問令牌從電子表格中讀取資料時,請求失敗并顯示 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);
uj5u.com熱心網友回復:
當我看到你的腳本時,我認為需要修改范圍。我遇到了和你一樣的情況(401使用你的端點的狀態碼)。不幸的是,您的端點似乎無法使用https://www.googleapis.com/auth/spreadsheets.readonly. 那么,例如,如何將其更改如下,然后再次測驗?
從:
https://www.googleapis.com/auth/spreadsheets.readonly
到:
https://www.googleapis.com/auth/spreadsheets
要么
https://www.googleapis.com/auth/drive.readonly
筆記:
- 當我使用修改后的范圍測驗您的端點時,我確認沒有發生錯誤。但是,如果您測驗過它并且發生錯誤時,請再次檢查其他部分。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/453678.html
標籤:javascript 谷歌表格 谷歌可视化
上一篇:資料驗證下拉選單中的默認值
