无法解构属性错误 - googleapi

时间:2018-05-28 10:05:32

标签: node.js callback promise gmail-api google-api-nodejs-client

使用googleapi时出错

我的错误:

  

(node:7776)UnhandledPromiseRejectionWarning:TypeError:无法解析' undefined'的属性data。或者' null'。       在gmail.users.labels.list

对我来说令人困惑的是,一切正常,它打印出它应该但是为什么它会给我一个关于如果显然不是null的错误? 怎么能解决这个问题?

这是我的代码:

var async = require('async-kit');
const fs = require('fs');
const readline = require('readline');
const {
  google
} = require('googleapis');

const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
const TOKEN_PATH = 'credentials.json';

function test(methodname) {
  console.log('called');
  fs.readFile('client_secret.json', (err, content) => {
    if (err) return console.log('Error loading client secret file:', err);
    // Authorize a client with credentials, then call the Google Sheets API.
    authorize(JSON.parse(content), methodname);
  });
}

/**
 * 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) {
  console.log('authorized');
  const {
    client_secret,
    client_id,
    redirect_uris
  } = credentials.installed;
  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 getNewToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(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 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 callback(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 labels in the user's account.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listLabels(auth, callback) {
  const gmail = google.gmail({
    version: 'v1',
    auth
  });
  gmail.users.labels.list({
    userId: 'me',
  }, (err, {
    data
  }) => {
    if (err) {
      console.log('The API returned an error: ' + err);
      callback();
    }
    const labels = data.labels;
    console.log('got labels');
    if (labels.length) {
      interimlabels = labels;
      interimlabels.forEach((label) => {
        console.log(`- ${label.name}`);
      });
      callback();
    }
    else {
      console.log('No labels found.');
      callback();
    }
  });
}
var interimlabels = [];
async.series([
    function getStuff(callback) {
      test(listLabels);
      if (interimlabels.length != 0) {
        console.log('labels', interimlabels);
        callback();
      }
    }
  ])
  .exec(function(error, results) {
    if (error) {
      console.log('shit');
    }
    else {
      console.log('done');
    }
  });

编辑:我只是想补充一点,它应该完整地注销,但应该在它结束后给我错误 edit2:好的,如果我删除回调();来自listLabels();然后,promise promise会消失,但代码显然会挂在那里,那么回调的问题是什么呢?

1 个答案:

答案 0 :(得分:0)

//您收到错误,并且在错误处理方面存在一些错误。你破坏了谷歌API的结果。但事实上你没有得到任何结果,所以它显示给定的错误:Cannot destructure propery error - googleapi

//试试这段代码。

/**
 * Lists the labels in the user's account.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listLabels(auth, callback) {
  const gmail = google.gmail({
    version: 'v1',
    auth
  });
  gmail.users.labels.list({
    userId: 'me',
  }, (err, result) => {
    if (err || !result) {
      console.log('The API returned an error: ' + err);
      callback();
    } else {
      const labels = result.data.labels;
      console.log('got labels');
      if (labels.length) {
        interimlabels = labels;
        interimlabels.forEach((label) => {
          console.log(`- ${label.name}`);
        });
        callback();
      }
      else {
        console.log('No labels found.');
        callback();
      }
    }
  });
}

希望这能解决您的问题。

更新代码:

function listLabels(auth, callback) {
  const gmail = google.gmail({
    version: 'v1',
    auth
  });

  var request = gmail.users.labels.list({
    'userId': 'me'
  });
  request.execute(function(resp) {
    console.log("resp", resp);
    var labels = resp.labels;
    callback(labels);
  });
}