【发布时间】:2021-09-29 16:26:33
【问题描述】:
我正在尝试访问 google sheet api,但首先我尝试使用以下代码生成访问令牌。
const { google } = require("googleapis");
getAccessToken = () => {
return new Promise(function(resolve, reject) {
const key = require('./credentials.json');
const jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
"https://www.googleapis.com/auth/spreadsheets",
null
);
jwtClient.authorize(function(err, tokens) {
if (err) {
reject(err);
return;
}
console.log("token===",tokens.access_token);
resolve(tokens.access_token);
});
});
};
getAccessToken();
但未能在 jwtClient.authorize() 授权 并得到如下错误:
C:\Google API\GoogleSheet UsingJWT\GoogleSheet UsingJWT>node index.js
(node:16820) UnhandledPromiseRejectionWarning: FetchError: request to https://www.googleapis.com/oauth2/v4/token failed, reason: getaddrinfo ENOTFOUND 808
at ClientRequest.<anonymous> (C:\Google API\GoogleSheet UsingJWT\GoogleSheet UsingJWT\node_modules\node-fetch\lib\index.js:1461:11)
at ClientRequest.emit (events.js:314:20)
at onerror (C:\Google API\GoogleSheet UsingJWT\GoogleSheet UsingJWT\node_modules\agent-base\dist\src\index.js:117:21)
at callbackError (C:\Google API\GoogleSheet UsingJWT\GoogleSheet UsingJWT\node_modules\agent-base\dist\src\index.js:136:17)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:16820) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:16820) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
我也没有使用任何代理。我无法理解实际问题。
谁能帮帮我?
【问题讨论】:
-
您好!我一直在研究你的脚本,但我没有发现任何明显的故障。我知道问题出在身份验证流程中,在这种情况下,我强烈建议您关注Node.js Sheets API quickstart,看看它是否有帮助。尤其是代码的前半部分,其中显示了工作身份验证流程。请对其进行测试,然后回来分享您的发现。
标签: javascript node.js google-sheets google-cloud-platform google-sheets-api