【问题标题】:googleapi/drive in node.jsnode.js 中的 googleapi/drive
【发布时间】:2022-01-17 17:33:25
【问题描述】:

我正在尝试使用 Node.js 集成 googleapi/drive,并且我需要在 React.js 中集成 API。

我面临的问题是我在前端收到了一些奇怪的错误消息。

我在 Node.js 中有以下代码。

      import { auth, drive } from "@googleapis/drive"
      ...
      const driveAuth = new auth.GoogleAuth({
        keyFilename: path.join(__dirname, '../oauth2.keys.json'),
        scopes: [
          'https://www.googleapis.com/auth/drive',
          'https://www.googleapis.com/auth/drive.appdata',
          'https://www.googleapis.com/auth/drive.file',
        ],
      })
      const authClient = await driveAuth.getClient()

      const driveService = await drive({
        auth: authClient,
      }).files.list()

如果我将此 API 集成到前端,则会收到错误消息。

message: "Unable to load endpoint drive(\"undefined\"): ctr is not a constructor"

如果我检查GoogleAuth 的控制台日志,则会得到以下信息。

JWT {
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  transporter: DefaultTransporter {},
  credentials: { refresh_token: 'jwt-placeholder', expiry_date: 1 },
  eagerRefreshThresholdMillis: 300000,
  forceRefreshOnFailure: false,
  certificateCache: {},
  certificateExpiry: null,
  certificateCacheFormat: 'PEM',
  refreshTokenPromises: Map(0) {},
  _clientId: undefined,
  _clientSecret: undefined,
  redirectUri: undefined,
  email: undefined,
  keyFile: 'E:\\work\\backend\\oauth2.keys.json',
  key: undefined,
  keyId: undefined,
  scopes: undefined,
  subject: undefined,
  additionalClaims: undefined,
  defaultServicePath: undefined,
  useJWTAccessWithScope: undefined,
  defaultScopes: undefined,
  [Symbol(kCapture)]: false
}

我的最终目标是在 google 驱动器中创建一个文件夹。

我已经在我的控制台中启用了 google drive api,并使用 OAuth2 客户端 ID 创建了一个凭据。

怎么了?我猜我的 GoogleAuth 失败了?

【问题讨论】:

    标签: node.js google-api google-drive-api google-oauth google-api-nodejs-client


    【解决方案1】:

    您需要提供要在服务中使用的 api 版本

    // Create a service account initialize with the service account key file and scope needed
    const auth = new google.auth.GoogleAuth({
        keyFile: KEYFILEPATH,
        scopes: SCOPES
    });
    const driveService = google.drive({version: 'v3', auth});
    

    Upload Image to Google drive with Node Js 窃取的代码

    【讨论】:

    • 感谢您的回答。顺便说一句,我只是将版本设置为 v3,现在我得到了key must be a string, a buffer or an object。我应该一一读取json文件中的行吗?有点烦人。
    • 您是否将 KEYFILEPATH 更新为您的密钥文件,因为您没有像我一样创建常量?
    • 这是真正的路径。如果我设置了错误的路径,那么它会失败。
    • 你的意思是我应该为它使用一个环境变量?
    • 似乎我应该使用服务帐户 json 文件而不是 auth 客户端 json。谢谢。
    猜你喜欢
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 2018-10-26
    • 2013-03-30
    • 2016-07-13
    相关资源
    最近更新 更多