Javascript 如果我这样做,为什么GoogleCalendarAPInodejs示例不起作用?

Javascript 如果我这样做,为什么GoogleCalendarAPInodejs示例不起作用?,javascript,node.js,google-calendar-api,Javascript,Node.js,Google Calendar Api,基于nodejs快速启动示例(凭证将替换为虚拟凭证) 以下是有效的代码: const fs = require('fs'); const mkdirp = require('mkdirp'); const readline = require('readline'); const {google} = require('googleapis'); const OAuth2Client = google.auth.OAuth2; const SCOPES = ['https://www.googl

基于nodejs快速启动示例(凭证将替换为虚拟凭证)

以下是有效的代码:

const fs = require('fs');
const mkdirp = require('mkdirp');
const readline = require('readline');
const {google} = require('googleapis');
const OAuth2Client = google.auth.OAuth2;
const SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'];
const TOKEN_PATH = 'credentials.json';

// Load client secrets from a local file.
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 Drive API.
  authorize(JSON.parse(content), listEvents);
});

/**
 * 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 OAuth2Client(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));

    // THIS WORKS IF ITS HERE AND PASSED IN CALLBACK
    let client = new OAuth2Client("484407463774-e7biatgmpns9jcpakr5g0sed8fab376u.apps.googleusercontent.com", "722_fI1u2abNM3tL-VbCuZfF", "http://localhost:1337/api/v1/oauthCallback");
    client.setCredentials({
      "access_token": "ya29.GluyBSUYvP_Gi4_SdJHabcJmXUjHnw34MfMBJ8tzROflqyR9dFMDOh_AYh9dmL4FSNDiva_nAcWYCM9m5jBwaL3pWfSm_wv0IybUUdebt66gDakdFXL0o8Mr-0Ge",
      "expiry_date": 1525551674971,
      "token_type": "Bearer",
      "refresh_token": "1/Ug8agC92PkJRXEDLP1inlHcAh4MBP1SLjNoylPJrmfg"
    });


    callback(client);
  });
}

/**
 * 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: '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) console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client).catch(console.error);
    });
  });
}

/**
 * Lists the next 10 events on the user's primary calendar.
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listEvents(auth) {

  const calendar = google.calendar({ version: 'v3', auth });
  calendar.events.list({
    calendarId: 'primary',
    timeMin: (new Date()).toISOString(),
    maxResults: 10,
    singleEvents: true,
    orderBy: 'startTime',
  }, (err, {data}) => {
    if (err) return console.log('The API returned an error: ' + err);
    const events = data.items;
    if (events.length) {
      console.log('Upcoming 10 events:');
      events.map((event, i) => {
        const start = event.start.dateTime || event.start.date;
        console.log(`${start} - ${event.summary}`);
      });
    } else {
      console.log('No upcoming events found.');
    }
  });


}
因此,在上面的代码中,我们首先从credentials.json文件中查找凭据。为了方便起见,我在
authorize()

但是如果我在
listEvents()
中移动上述行,如下所示:

const fs = require('fs');
const mkdirp = require('mkdirp');
const readline = require('readline');
const {google} = require('googleapis');
const OAuth2Client = google.auth.OAuth2;
const SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'];
const TOKEN_PATH = 'credentials.json';

// Load client secrets from a local file.
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 Drive API.
  authorize(JSON.parse(content), listEvents);
});

/**
 * 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 OAuth2Client(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));


    callback(null);
  });
}

/**
 * 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: '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) console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client).catch(console.error);
    });
  });
}

/**
 * Lists the next 10 events on the user's primary calendar.
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listEvents(auth) {
 // THIS DOES NOT WORK 
 let client = new OAuth2Client("480557463774-e7biatgmpns9jcpakran0sed8f55376u.apps.googleusercontent.com", "722_fBsu2ECNM3tL-VbCuZfF", "http://localhost:1337/api/v1/oauthCallback");
  client.setCredentials({
    "access_token": "ya29.GluyBSUYvP_Gi4_SdJHsuPJmXUjHdd34MfMBJ8tzROflqyR9dFMDOh_AYh9dmL4FSNDiva_nAcWYCM9m5jBwaL3pWfSm_wv0IybUUORbt66gDakdFXL0o8Mr-0Ge",
    "expiry_date": 1525551674971,
    "token_type": "Bearer",
    "refresh_token": "1/Ug8MhC92ddJRXEDLP1inlHcAh4MBP1SLjNoylPJrmfg"
  });

  const calendar = google.calendar({ version: 'v3', client });
  calendar.events.list({
    calendarId: 'primary',
    timeMin: (new Date()).toISOString(),
    maxResults: 10,
    singleEvents: true,
    orderBy: 'startTime',
  }, (err, {data}) => {
    if (err) return console.log('The API returned an error: ' + err);
    const events = data.items;
    if (events.length) {
      console.log('Upcoming 10 events:');
      events.map((event, i) => {
        const start = event.start.dateTime || event.start.date;
        console.log(`${start} - ${event.summary}`);
      });
    } else {
      console.log('No upcoming events found.');
    }
  });


}
然后它不再工作,并出现以下错误:

(node:95252) UnhandledPromiseRejectionWarning: TypeError: Cannot destructure property `data` of 'undefined' or 'null'.
    at calendar.events.list (C:\Users\rahulserver\Desktop\gcalapinodejs\quickstart.js:87:6)
    at C:\Users\rahulserver\Desktop\gcalapinodejs\node_modules\google-auth-library\build\src\transporters.js:74:17
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
(node:95252) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside o
f an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:95252) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections tha
t are not handled will terminate the Node.js process with a non-zero exit code.
(节点:95252)未处理的PromisejectionWarning:TypeError:无法对“undefined”或“null”的属性“data”进行解构。
在calendar.events.list(C:\Users\rahulserver\Desktop\gcalapinodejs\quickstart.js:87:6)
在C:\Users\rahulserver\Desktop\gcalapinodejs\node\u modules\google auth library\build\src\transporters.js:74:17
在
在进程中。_tick回调(内部/process/next_tick.js:188:7)
(节点:95252)未处理的PromisejectionWarning:未处理的承诺拒绝。此错误源于
f不带catch块的异步函数,或拒绝未使用.catch()处理的承诺。(拒绝id:2)
(节点:95252)[DEP0018]弃用警告:未处理的承诺拒绝已弃用。在未来,承诺拒绝
t未处理将使用非零退出代码终止Node.js进程。
在我看来,无论哪种情况,我都在做同样的事情。在第一种情况下,我将客户机作为参数传递给回调。第二,我将null传递给回调,并在回调本身中实例化oauth客户机。
不确定在第二种方法中发生了什么“神秘”的事情,使得代码不再工作。

您遇到了某种错误,这使得从
calendar.events.list()调用的第二个参数未定义

请记住,此回调的形式为
(err,{data})=>{
,因此如果出现错误,您将不会有第二个参数。但是,您仍在尝试对其进行解构,因此会出现错误

简单的修复方法是应用默认参数。这将使其在发生错误时使用空对象:

(err, { data } = {}) => {
或者,您可以在错误检查后对其进行解构。就我个人而言,我是默认参数的粉丝


一旦您做出了更改,您将能够看到错误是什么。希望该消息将使剩余的问题更容易解决。

我已经解决了

而不是
const calendar=google.calendar({version:'v3',client});

应该是
const calendar=google.calendar({version:'v3',auth:client});


因此es6对象速记语法有时会令人困惑!

谢谢你的回答。我实际上能够看到消息(使用vscode IDE中的node js调试器).
API返回了一个错误:错误:超出了未经验证使用的每日限制。继续使用需要注册。
问题是,如果我只是将回调参数替换为局部变量,结果会有什么不同??
(err, { data } = {}) => {