我正在尝试在 Node 中制作一个应用程序来访问我的谷歌日历,所以我按照 https://developers.google.com/calendar/quickstart/nodejs 中的步骤进行了操作。但我收到了 Error: Error: No access, refresh token or API key is set.
.
是的,我已经创建了凭据。
是的,我已经下载了 json,重命名为 client_secret.json 并添加到应用程序文件夹中。
这是代码:
const fs = require('fs');
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 = './client_secret.json';
try {
const content = fs.readFileSync('client_secret.json');
authorize(JSON.parse(content), listEvents);
} catch (err) {
return console.log('Error loading client secret file:', err);
}
function authorize(credentials, callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
let token = {};
const oAuth2Client = new OAuth2Client(client_id, client_secret, redirect_uris[0]);
// Check if we have previously stored a token.
try {
token = fs.readFileSync(TOKEN_PATH);
} catch (err) {
return getAccessToken(oAuth2Client, callback);
}
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
}
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
try {
fs.writeFileSync(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to', TOKEN_PATH);
} catch (err) {
console.error(err);
}
callback(oAuth2Client);
});
});
}
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.');
}
});
}
有任何想法吗?
最佳答案
您能再次确认以下几点吗?
const TOKEN_PATH = './client_secret.json';
的文件和 const content = fs.readFileSync('client_secret.json');
是相同的。const TOKEN_PATH = './client_secret.json';
修改至 const TOKEN_PATH = './credentials.json';
,然后再次运行。 client_secret.json
您下载的可能已经被覆盖。所以也请确认这一点。 引用 :
如果这些要点对您的情况没有用,我很抱歉。
关于google-calendar-api - 设置了错误 : No access, 刷新 token 或 API key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50281159/