【问题标题】:GoogleSheet API Error: FetchError: request to https://www.googleapis.com/oauth2/v4/token failed, reason: getaddrinfo ENOTFOUND 808GoogleSheet API 错误:FetchError:对 https://www.googleapis.com/oauth2/v4/token 的请求失败,原因:getaddrinfo ENOTFOUND 808
【发布时间】: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


【解决方案1】:

我了解到您想为您的 Sheets API Node.js 脚本生成一个OAuth 2.0 token flow,但您收到一个错误作为响应。该错误消息描述了此问题如何源自未处理的承诺。要解决这种情况,您应该使用handled promises。一种方法是使用以下示例:

const fs = require('fs');
const readline = require('readline');
const {
  google
} = require('googleapis');

const SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
const TOKEN_PATH = 'token.json';

fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  authorize(JSON.parse(content), myFunction);
});

function authorize(credentials, callback) {
  const {
    client_secret,
    client_id,
    redirect_uris
  } = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
    client_id, client_secret, redirect_uris[0]);

  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getNewToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

function getNewToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error(
        'Error while trying to retrieve access token', err);
      oAuth2Client.setCredentials(token);
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

function myFunction(auth) {
  // YOUR CODE HERE
}

该脚本将达到您所描述的目标,您只需记住更改scope(如果需要)并更新myFunction。如果您需要有关此方法的帮助,请随时发表评论。

【讨论】:

    猜你喜欢
    • 2019-07-23
    • 2020-08-10
    • 2021-06-19
    • 2021-01-18
    • 2019-09-13
    • 2019-11-02
    • 2021-08-10
    • 2021-09-10
    • 1970-01-01
    相关资源
    最近更新 更多