javascript - 如果我这样做,为什么 google calendar api nodejs 示例不起作用?

标签 javascript node.js google-calendar-api

基于nodejs快速入门示例(凭证被替换为虚拟凭证)here

以下是有效的代码:

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()

中对它们进行了硬编码
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"
        });

但是如果我将上面的行移动到 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.

IMO 在这两种情况下我都会做同样的事情。在第一种情况下,我将客户端作为参数传递给回调。其次,我将 null 传递给回调,并在回调本身中实例化 oauth 客户端。 不确定第二种方法中发生了什么“神秘”的事情,导致代码不再工作。

最佳答案

您遇到某种错误,这使得来自 calendar.events.list() 回调中的第二个参数未定义

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

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

(err, { data } = {}) => {

或者,您可以在错误检查后对其进行解构。就我个人而言,我很喜欢默认参数。

完成更改后,您将能够看到错误所在。希望该消息将使剩余的问题易于解决。

关于javascript - 如果我这样做,为什么 google calendar api nodejs 示例不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50204422/

相关文章:

javascript - 如何使用 date-fns 查找一周中最近的一天

javascript - 修改现有的 Google 日历事件

javascript - 谷歌日历 API v3 : events from a particular week

javascript - if 11pm 调用函数更改表单输入值

javascript - 如何将 Google 标签管理器与 React Native 应用程序集成?

javascript - 轨道 slider : Captions Not Displaying

javascript - 将函数附加到 JavaScript 对象文字的 __proto__ 属性是否是个好主意?

Node.js - writeHead 设置 "Location"和 "Set-Cookie"

node.js - appjs 或node-webkit 如何将nodejs 和CEF 结合在一起?

google-calendar-api - 如何使用 ASP.Net/C# 覆盖嵌入式谷歌日历上的 CSS?