1

I am trying to access my google drive Files through the API. I'm using the google drive API code that was given to me in the Node.js quickstart, and altered it to suit my needs. I need the access token to be able activate this listFiles() function, using the auth argument given to it by the authorize() function. I'll paste the whole logic here so you can see.

These are some of the errors I'm getting:

(node:6844) UnhandledPromiseRejectionWarning: Error: invalid_request at Gaxios. at Generator.next () (node:6844) 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(). (rejection id: 1)

Here's the code. I want to console.log the driveFiles in the listFiles() function, and I have a token.json to read from. I don't know what the problem is.

index.js:

const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
const { file } = require('googleapis/build/src/apis/file');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';

// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Drive API.
  authorize(JSON.parse(content), listFiles());
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.web;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    listFiles(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getAccessToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'online',
    scope: SCOPES,
    response_type: 'token',
  });
  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 retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}



/**
 * Lists the names and IDs of up to 10 files.
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */

async function listFiles(auth) {
  const drive = google.drive({ version: "v3", auth });
  const res = await drive.files.list({
    pageSize: 10,
    fields: "nextPageToken, files(id, name, description, mimeType, createdTime, parents, properties)",
  });
  const files = res.data.files;
  const fileArray = [];
  if (files.length) {
    const fileDisplay = [];
    const fileIdArray = [];
    const mimeType = [];
    const parents = [];
    const properties = [];
    console.log("Files:");
    for (var i = 0; i < files.length; i++) {
      fileDisplay.push(files[i].name);
      fileIdArray.push(files[i].id);
      mimeType.push(files[i].mimeType);
      properties.push(files[i].properties);
      parents.push(files[i].parents);
    }
    for (var y = 0; y < fileDisplay.length; y++) {
      fileArray.push({
        file: fileDisplay[y],
        id: fileIdArray[y],
        type: mimeType[y],
        parents: parents[y],
        properties: properties[y],
      });
    }
    app.set('fileArray', fileArray);
    console.log(fileArray)
  }
}

Token.json:

{"access_token":"***","scope":"https://www.googleapis.com/auth/drive","token_type":"Bearer","expiry_date":3599}

Really need some help. My client is getting upset.

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
Matt.G
  • 171
  • 2
  • 7
  • Could you look at the Network-Tab how the request and respond looks like? And Share it with us, to be able to help you? – Nikolaus Aug 23 '20 at 19:15
  • It looks like the promise in the last async function is getting rejected, can you try wrapping the await statement in a `try catch` and log the error that you get? – Spack Jarrow Aug 23 '20 at 19:54
  • if you look at the answer here https://stackoverflow.com/questions/19766912/how-do-i-authorise-an-app-web-or-installed-without-user-intervention there is working code that is equivalent to your sample. The two differences are (1) it uses a refresh token rather than token.json and (2) it doesn't use any library dependencies – pinoyyid Aug 24 '20 at 00:30
  • Did it work before you altered it? – Linda Lawton - DaImTo Aug 24 '20 at 06:41
  • (1) what line are you getting the error at?, (2) what changes did you make to the quickstart code to suit your needs?, (3) remove the `()` from `listFiles` here: `authorize(JSON.parse(content), listFiles());`, (4) shouldn't `listFiles(oAuth2Client);` be `callback(oAuth2Client)` instead? – Iamblichus Aug 25 '20 at 09:52

0 Answers0