Search code examples
node.jsgoogle-apigoogle-drive-apigoogle-oauthgoogle-api-nodejs-client

googleapi/drive in node.js


I am trying to integrate googleapi/drive using Node.js and also I need to integrate the API in React.js.

What issue I am facing into is that I am getting a couple of weird error messages in the front-end.

I have the following codes in 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()

If I integrate this API in the front-end, then I get a error message.

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

If I check the console log for the GoogleAuth, then I get the following.

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
}

My final goal is to create a folder in the google drive.

I already enabled google drive api in my console, and created a credential using OAuth2 Client ID.

What's wrong? I guess my GoogleAuth is failed?


Solution

  • You need to supply the version of the api you want to use in the service

    // 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});
    

    Code ripped from Upload Image to Google drive with Node Js