为什么我的Google API访问密钥不起作用?

问题描述

我正在尝试通过API访问我的Google驱动器文件。我正在使用Node.js quickstart中提供给我的Google Drive API代码,并对其进行了更改以满足我的需要。我需要访问令牌才能使用authorize()函数赋予它的auth参数来激活此listFiles()函数。我将整个逻辑粘贴在这里,以便您查看。

这些是我遇到的一些错误

(节点:6844)UnhandledPromiseRejectionWarning:错误:invalid_request 在Gaxios。在Generator.next()(节点:6844) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这个 由抛出异步函数引起的错误 没有障碍,或者拒绝没有处理的承诺 使用.catch()。 (拒绝ID:1)

这是代码。我想在listFiles()函数中console.log driveFiles,并且我有一个token.json要读取。我不知道问题是什么。

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,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,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}

真的需要一些帮助。我的客户不高兴。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)