使用 NodeJS 在 google 日历 api 上创建事件时缺少结束时间错误
Error missing end time when create event on google calendar api using NodeJS
我在使用 nodejs 在 google 日历 api 中创建事件时遇到问题。具体来说,我成功地获取了 google 日历中的事件列表,但无法创建该事件,并且显示“缺少结束时间”错误。下面是我的代码,我参考了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;
我尝试修复,但代码在创建事件时仍然显示 "Missing end time" 错误,1 周过去了,我还无法修复它。期待您的帮助。
进行以下更改 -
var {google} = require('googleapis');
而不是 var google = require('googleapis');
写var OAuth2 = google.auth.OAuth2;
而不是var googleAuth = require('google-auth-library');
不要npm install google-auth-library
。如果这样做,请将其从 package.json 中删除并再次执行 npm install
。
确保您拥有最新版本的 googleapis
软件包。如果您不这样做 - 请执行 npm install googleapis@27
以获取它。 (也将其添加到 package.json 以备将来使用)。
对于任何回调 - 而不是 response.items
,请执行 response.data.items
。创建事件时不一定需要回调输出,但列出事件时肯定需要它。所以不要忘记在那里进行更改。
我认为您按照所有这些步骤操作后不会有任何问题。如果还有,就回复这个。我会尽力解决的!
我有同样的问题,我只是被撤销了我的第三方应用程序的帐户访问权限。这对我有用
我在使用 nodejs 在 google 日历 api 中创建事件时遇到问题。具体来说,我成功地获取了 google 日历中的事件列表,但无法创建该事件,并且显示“缺少结束时间”错误。下面是我的代码,我参考了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;
我尝试修复,但代码在创建事件时仍然显示 "Missing end time" 错误,1 周过去了,我还无法修复它。期待您的帮助。
进行以下更改 -
var {google} = require('googleapis');
而不是var google = require('googleapis');
写
var OAuth2 = google.auth.OAuth2;
而不是var googleAuth = require('google-auth-library');
不要
npm install google-auth-library
。如果这样做,请将其从 package.json 中删除并再次执行npm install
。确保您拥有最新版本的
googleapis
软件包。如果您不这样做 - 请执行npm install googleapis@27
以获取它。 (也将其添加到 package.json 以备将来使用)。对于任何回调 - 而不是
response.items
,请执行response.data.items
。创建事件时不一定需要回调输出,但列出事件时肯定需要它。所以不要忘记在那里进行更改。
我认为您按照所有这些步骤操作后不会有任何问题。如果还有,就回复这个。我会尽力解决的!
我有同样的问题,我只是被撤销了我的第三方应用程序的帐户访问权限。这对我有用