【发布时间】:2022-01-18 07:35:31
【问题描述】:
我有异步函数 getTables(),它使用 Google Sheet API 来获取 google 电子表格数据。但是在响应时它返回未定义的值。 this.getClient() 返回 OAuth2Client 数据。你能检查我的异步函数,也许它写得不对?
async getTables(): Promise<any> {
try {
const sheets = google.sheets({
version: "v4",
auth: await this.getClient()
});
const res = await sheets.spreadsheets.values.get({
spreadsheetId: "sheetId",
range: "A1:B100"
});
return res;
} catch (err) {
throw new HttpException("The API returned an error: " + err, 500);
}
这是授权客户端的getClient异步函数。
async getClient(): Promise<OAuth2Client> {
if (!this.oAuth2Client) {
return await this.authorize();
}
return this.oAuth2Client;
}
private async authorize() {
const credentials = {
access_token: this.auth.access_token,
refresh_token: null
};
this.oAuth2Client = new google.auth.OAuth2(this.CLIENT_ID, this.clientSecret, this.redirectUrl);
this.oAuth2Client.setCredentials(credentials);
return this.oAuth2Client;
}
【问题讨论】:
-
是什么让你认为它返回未定义?您能否提供一个可重现的最小示例,包括您调用
getTables()的上下文以及您如何检查它是否返回未定义? -
@Iamblichus 我记录了响应(res),它显示未定义。
@Get() async getSpreadSheet(): Promise<any> { return await this.spreadService.getTables() }我在控制器中调用 getTables()。 -
能否提供
getClient相关的代码?如果您删除异步部分,您会得到相同的行为吗? -
@Iamblichus 我更新了上面的代码,您可以在其中看到 getClient 函数。
-
谢谢。正如我之前提到的,您是否尝试删除异步部分?你有同样的行为吗?
标签: google-api nestjs google-sheets-api