使用NodeJS在Google日历api上创建活动时错过结束时间错误

时间:2018-02-10 12:34:51

标签: node.js google-apis-explorer

使用nodejs在google calendar api中创建事件时遇到问题。具体来说,我成功获取了谷歌日历中的事件列表但无法创建事件,并显示“缺少结束时间”错误。以下是我的代码,我参考了google calendar api说明:

var express = require('express');
var router = express.Router();
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/calendar-nodejs-quickstart.json
var SCOPES = [
    'https://www.googleapis.com/auth/calendar'
];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'quickstart.json';
console.log(TOKEN_PATH);

// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
    if (err) {
        console.log('Error loading client secret file: ' + err);
        return;
    }
    // Authorize a client with the loaded credentials, then call the
    // Google Calendar API.
    authorize(JSON.parse(content), listEvents);
    authorize(JSON.parse(content), addEvents);
});

/**
 * 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) {
    var clientSecret = credentials.installed.client_secret;
    var clientId = credentials.installed.client_id;
    var redirectUrl = credentials.installed.redirect_uris[0];
    var auth = new googleAuth();
    var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

    // Check if we have previously stored a token.
    fs.readFile(TOKEN_PATH, function(err, token) {
        if (err) {
            getNewToken(oauth2Client, callback);
        } else {
            oauth2Client.credentials = 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 to call with the authorized
 *     client.
 */
function getNewToken(oauth2Client, callback) {
    var authUrl = oauth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: SCOPES
    });
    console.log('Authorize this app by visiting this url: ', authUrl);
    var rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    rl.question('Enter the code from that page here: ', function(code) {
        rl.close();
        oauth2Client.getToken(code, function(err, token) {
            if (err) {
                console.log('Error while trying to retrieve access token', err);
                return;
            }
            oauth2Client.credentials = token;
            storeToken(token);
            callback(oauth2Client);
        });
    });
}

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
    try {
        fs.mkdirSync(TOKEN_DIR);
    } catch (err) {
        if (err.code != 'EEXIST') {
            throw err;
        }
    }
    fs.writeFile(TOKEN_PATH, JSON.stringify(token));
    console.log('Token stored to ' + TOKEN_PATH);
}

/**
 * Lists the next 10 events on the user's primary calendar.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listEvents(auth) {
    var calendar = google.calendar('v3');
    calendar.events.list({
        auth: auth,
        calendarId: 'primary',
        timeMin: (new Date()).toISOString(),
        maxResults: 10,
        singleEvents: true,
        orderBy: 'startTime'
    }, function(err, response) {
        if (err) {
            console.log('The API returned an error: ' + err);
            return;
        }
        var events = response.items;
        if (events.length == 0) {
            console.log('No upcoming events found.');
        } else {
            console.log('Upcoming 10 events:');
            for (var i = 0; i < events.length; i++) {
                var event = events[i];
                var start = event.start.dateTime || event.start.date;
                var end = event.end.dateTime || event.end.date;
                console.log('%s - %s', start, event.summary);
                console.log('%s', end);
            }
        }
    });
}

function addEvents(auth){
    var calendar = google.calendar('v3');
    var event = {
        'summary': 'Drinking beer with friends',
        'start': {
            'dateTime': '2018-02-09T09:00:00+07:00'
        },
        'end': {
            'dateTime': '2018-02-09T17:00:00+07:00'
        }
    };
    calendar.events.insert({
        auth: auth,
        calendarId: 'primary',
        resource: event,
    }, function(err, event) {
        if (err) {
            console.log('There was an error contacting the Calendar service: ' + err);
            return;
        }
        console.log('Event created: %s', event.htmlLink);
    });
}


/* GET home page. */
/*console.log('ok');
router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });

});*/

module.exports = router;

我尝试修复,但是当我创建事件时代码仍然显示“缺少结束时间”错误,过了1周我还无法修复它。期待您的帮助。

2 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,只是我撤消了具有帐户访问权限的第三方应用程序的访问权限。对我有用

答案 1 :(得分:0)

进行以下更改 -

  1. var {google} = require('googleapis');代替var google = require('googleapis');

  2. 撰写var OAuth2 = google.auth.OAuth2;代替var googleAuth = require('google-auth-library');

  3. 不要npm install google-auth-library。如果您这样做,请将其从package.json中删除,然后再次npm install

  4. 确保您拥有最新版本的googleapis包。如果你不这样做 - 做npm install googleapis@27来获得它。 (也将它添加到package.json中以备将来使用。)

  5. 对于任何回调 - 而不是response.items,请执行response.data.items。创建事件时,您不一定需要回调输出,但在列出事件时肯定需要它。所以不要忘记在那里进行这种改变。

  6. 一旦您完成所有这些步骤,我认为不会有任何问题。如果还有,请回复此问题。我会尽力让它解决!