作为一名 javascript/node.js/express.js 新手,我正在为这个问题绞尽脑汁。查看“Google Calendar API Node.js Quickstart ”,我在运行 node Quickstart.js
时成功打印了即将发生的事件的列表。我现在想通过将数据传递到 View 渲染器来在浏览器中呈现该数据。我已将 Quickstart.js 中的代码复制到我的 routes/calendar.js 文件中。这是routes/calendar.js目前的样子:
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.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'calendar-nodejs-quickstart.json';
/**
* 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);
}
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;
console.log('%s - %s', start, event.summary);
}
}
});
}
/* GET events listing. */
router.get('/', function(req, res, next) {
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);
});
// TODO: How can I pass 'events' from 'listEvents' into the view renderer?
res.render('calendar', { title: 'TS Calendar', current: 'calendar', events: events });
});
module.exports = router;
当我访问http://localhost:3000/calendar时在我的浏览器中,我确实收到了有关“事件”未定义的错误,但我的控制台确实打印出了日历事件,所以我知道它至少在某种程度上起作用。
在我看来,这只是一堆回调,我无法完全理解如何从 listEvents 中提取/存储
因此它可以在 var events = response.items;
()router.get()
中使用。有什么建议么?一个很好的例子就太好了。
另外,为了奖励积分,我有点厌倦将所有这些逻辑/代码包含到 routes/calendar.js 文件中。有没有更expressjs风格的或者合适的地方?
最佳答案
我想我的心态是错误的。相反,我使用客户端 JavaScript 并使用 quickstart guide为了那个原因。我在这条路线上取得了进展,但我有一种感觉,我很快就会发现它不太适合没有键盘进行身份验证的信息亭应用程序。当我到达那个点时可能需要问这个问题。
关于node.js - 在 Express.js 应用程序中存储来自 Google 日历 Node.js 示例的事件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40313508/