- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
对于这个问题,我提前表示歉意。我知道这有点乱,但我只是迷失了,不再确定自己在问什么。如果您需要澄清,请随时提出任何问题!
我目前正在使用您的 Google Calendar API。我需要有关 NodeJS 集成的帮助。我需要提取一些有关包含假期日期信息的日历的数据。
我似乎收到错误消息:“API 返回错误:错误:超出未经身份验证使用的每日限制。继续使用需要注册。”
我尝试寻找对此的明确答案问题以及如何解决它。但 StackOverflow 或 Google 指南都没有帮助我了解我需要做什么,以及我的应用程序和 Google 日历 API 之间的实际连接是什么/在哪里。
我还尝试重构您页面上的 NodeJS 快速入门指南中的示例代码,以便我可以返回一个包含带有日期名称和描述的日历对象的数组。这会产生未定义的结果。因此,我基本上需要的是帮助检查我的代码中出错的地方,并重新评估身份验证过程,因为我已经设置了我的 secret 凭证,并将来自 API 的 token 保存到我的机器上。
所以我有我的代码,当我调用我的日历 Controller 来检索数据时,我得到未定义
返回并出现错误
快速启动代码:https://developers.google.com/calendar/quickstart/nodejs
我的日历 Controller 类:
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
const SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'];
const TOKEN_PATH = __dirname + '/token.json';
class CalendarController {
/**
* Create an OAuth2 client with the given credentials.
* @param {Object} credentials The authorization client credentials.
*/
getOAuth2Client(credentials) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return this.getNewAccessToken(oAuth2Client);
oAuth2Client.setCredentials(JSON.parse(token));
return oAuth2Client;
});
}
/**
* Get and store new token after prompting for user authorization.
* @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
*/
getNewAccessToken(oAuth2Client) {
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 the webpage here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', 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);
});
});
return oAuth2Client;
});
}
/**
* Lists the next maxResults events on the user's primary calendar.
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
listEvents(auth) {
const calendar = google.calendar({version: 'v3', auth});
let vacation_events = [];
calendar.events.list({
calendarId: 'CALENDAR.ID.IS.OMITTED.CUZ.DUH',
timeMin: (new Date()).toISOString(),
maxResults: 250,
singleEvents: true,
orderBy: 'startTime',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const events = res.data.items;
if (events.length) {
events.map((event, i) => {
const start = event.start.dateTime || event.start.date;
const end = event.end.dateTime || event.end.date;
let vacation = {
event_title: event.summary,
event_description: event.description,
dt_start: start,
dt_end: end,
}
vacation_events.push(vacation);
});
console.log(vacation_events);
return vacation_events;
} else {
console.log('No upcoming events found.');
}
});
}
getData() {
fs.readFile(__dirname + '/credentials.json', (err, content) => {
if (err) return console.error('Error loading client secrect file: ', err);
console.log(
this.listEvents(this.getOAuth2Client(JSON.parse(content)))
);
// return this.listEvents(this.getOAuth2Client(JSON.parse(content)));
})
}
}
module.exports = CalendarController;
说清楚一点。我的项目中确实有 credentials.json
和 token.json
文件并保存到我的计算机上。
最佳答案
所以我最终求助于 friend 。这导致了以下解决方案。
我的问题之一是,当您使用 Google 的 NodeJS 快速入门连接到日历 API 时,该代码会要求您通过浏览器手动更新 token 。所以我们必须解决这个问题。我遇到的第二个问题是我的代码没有按正确的顺序执行。正如 JS 中的许多事情一样,这是一个异步/等待问题。
如果您想使用单个用户自动执行此操作,以下文件显示了针对 Google Calendar API 的“正确”身份验证背后的代码逻辑。
const http = require('http')
const fs = require('fs')
const moment = require('moment')
const jwt = require('jsonwebtoken')
const { google } = require('googleapis')
const { GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REDIRECT_URIS } = process.env
const scope = ['https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/plus.login',
'https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile']
// adminID omitted
const adminID = '123456789101112131415'
const auth = new google.auth.OAuth2(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REDIRECT_URIS)
google.options({ auth })
const calendar = google.calendar({version: 'v3'})
const publicMethods = {
async listAllUpcomingEvents() {
const { data } = await calendar.events.list({
// correct calendarId omitted
calendarId: 'primary',
timeMin: (new Date()).toISOString(),
maxResults: 10,
singleEvents: true,
orderBy: 'startTime'
})
return data
}
/* Make all your calendar methods like shown here */
}
auth.on('tokens', (tokens) => {
if(verifyTokenId(tokens)) {
saveTokens(tokens)
}
})
function saveTokens (tokens) {
auth.setCredentials(tokens)
nDebug('auth:token', tokens)
tokenStore.tokens = tokens
}
/**
* Generate a url for authentication
*
* @returns {string} Authentication url
*/
function getUrl () {
return auth.generateAuthUrl({
access_type: 'offline',
prompt: 'consent',
scope
})
}
/**
* Store token upon oauth callback
*
* @param {string} code Access code from auth callback
* @returns {Object} tokens
*/
async function tokenCallback(code) {
const { tokens } = await auth.getToken(code)
return tokens
}
/**
* Acquires profile information and verifies ID against adminID
*
* @param {Object} tokens
* @returns {Boolean}
*/
async function verifyTokenId (tokens) {
const info = jwt.decode(tokens.id_token)
//const info = await auth.getTokenInfo(tokens.access_token)
return info.sub === adminID
}
function getRouter () {
const router = require('express').Router()
router.get('/redirect', (req, res) => {
res.redirect(getUrl())
})
router.get('/kappa', async (req, res) => {
const data = await publicMethods.listAllUpcomingEvents() /* Use calendar functions like this */
res.send(data)
})
router.get('/', async (req, res) => {
try {
const tokens = await tokenCallback(req.query.code)
nDebug('tokens', tokens)
if (!verifyTokenId(tokens)) {
return res.status(403).send(http.STATUS_CODES['403'])
}
return res.send(info)
} catch (e) {
nDebug('error', e.data || e)
res.status(500).send(e.data || e)
}
})
return router
}
/**
* Debugging class
*
* @param {string} string describing who calls the function
* @param {function} callback function
*/
function nDebug (who, what) {
console.log(moment().format(), who)
console.dir(what, {color: true, depth: 3})
console.log('#/', who)
}
/**
* Singleton class to store and retrieve tokens
*
* @class TokenStore
*/
class TokenStore {
/**
* Creates an instance of TokenStore.
* @param {Object} tokens - Collection of tokens to store
* @param {string} tokens.access_token - Access token
* @param {string} tokens.refresh_token - Refresh token
* @memberof TokenStore
*/
constructor (tokens) {
this._tokens = tokens
}
/**
* Returns stored tokens
*
* @memberof TokenStore
*/
get tokens () {
return this._tokens
}
/**
* Set tokens on TokenStore and writes them to file
*
* @memberof TokenStore
*/
set tokens (tokens) {
this._tokens = tokens
TokenStore.saveToFile(tokens)
}
/**
* Tries to load tokens from file, creates a blank TokenStore if none was found
*
* @static
* @returns {TokenStore} New instance of TokenStore
* @memberof TokenStore
*/
static tryLoadOrMakeNew () {
try {
const data = this.loadFromFile()
nDebug('token loaded', data)
setImmediate(() => saveTokens(data))
return new this(data)
} catch (err) {
if(err.code === 'ENOENT') {
nDebug('no token loaded', {})
return new this()
} else {
throw err /* Bollocks, something more serious is wrong, better throw up */
}
}
}
static loadFromFile () {
return JSON.parse(fs.readFileSync(this.filePath(), this.opts()))
}
static saveToFile (tokens) {
return fs.writeFileSync(this.filePath(), JSON.stringify(tokens, null, 2), this.opts())
}
static opts () {
return { encoding: 'utf-8' }
}
static filePath () {
return 'tokens.json'
}
}
/* I feel ashamed */
const tokenStore = TokenStore.tryLoadOrMakeNew()
module.exports = Object.assign(google, publicMethods, { getRouter })
最后,当我们收到 Google 的响应并获取刷新 token 和 access_token 时,我们会将其本地存储到“token.json”文件中。
请注意,如果您使用 nodemon
运行应用程序,则必须将 package.json
中的 npm start
更改为 ” start": "nodemon --ignore 'tokens.json' app.js"
如果评论中出现问题和更正,我会更新答案。
关于javascript - NodeJS、Google 日历 API 集成未经过身份验证并返回未定义,无论凭证和 token 是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53262053/
按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
在编码时,我问了自己这个问题: 这样更快吗: if(false) return true; else return false; 比这个? if(false) return true; return
如何在逻辑条件下进行“返回”? 在这样的情况下这会很有用 checkConfig() || return false; var iNeedThis=doSomething() || return fa
这是我的正则表达式 demo 如问题所述: 如果第一个数字是 1 则返回 1 但如果是 145 则返回 145 但如果是 133 则返回 133 样本数据a: K'8134567 K'81345678
在代码高尔夫问答部分查看谜题和答案时,我遇到了 this solution返回 1 的最长和最晦涩的方法 引用答案, int foo(void) { return! 0; } int bar(
我想在下面返回 JSON。 { "name": "jackie" } postman 给我错误。说明 Unexpected 'n' 这里是 Spring Boot 的新手。 1日龄。有没有正确的方法来
只要“is”返回 True,“==”不应该返回 True 吗? In [101]: np.NAN is np.nan is np.NaN Out[101]: True In [102]: np.NAN
我需要获取所有在 6 号或 7 号房间或根本不在任何房间的学生的详细信息。如果他们在其他房间,简单地说,我不希望有那个记录。 我的架构是: students(roll_no, name,class,.
我有一个表单,我将它发送到 php 以通过 ajax 插入到 mysql 数据库中。一切顺利,php 返回 "true" 值,但在 ajax 中它显示 false 消息。 在这里你可以查看php代码:
我在 Kotlin 中遇到了一个非常奇怪的无法解释的值比较问题,以下代码打印 假 data class Foo ( val a: Byte ) fun main() { val NUM
请注意,这并非特定于 Protractor。问题在于 Angular 2 的内置 Testability service Protractor 碰巧使用。 Protractor 调用 Testabil
在调试窗口中,以下表达式均返回 1。 Application.WorksheetFunction.CountA(Cells(4 + (i - 1) * rows_per_record, 28) & "
我在本地使用 jsonplaceholder ( http://jsonplaceholder.typicode.com/)。我正在通过 extjs rest 代理测试我的 GET 和 POST 调用
这是 Postman 为成功调用我的页面而提供的(修改后的)代码段。 var client = new RestClient("http://sub.example.com/wp-json/wp/v2
这个问题在这里已经有了答案: What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must
我想我对 C 命令行参数有点生疏。我查看了我的一些旧代码,但无论这个版本是什么,都会出现段错误。 运行方式是 ./foo -n num(其中 num 是用户在命令行中输入的数字) 但不知何故它不起作用
我已经编写了一个类来处理命名管道连接,如果我创建了一个实例,关闭它,然后尝试创建另一个实例,调用 CreateFile() 返回 INVALID_HANDLE_VALUE,并且 GetLastErro
即使 is_writable() 返回 true,我也无法写入文件。当然,该文件存在并且显然是可读的。这是代码: $file = "data"; echo file_get_contents($fil
下面代码中的变量 $response 为 NULL,尽管它应该是 SOAP 请求的值。 (潮汐列表)。当我调用 $client->__getLastResponse() 时,我从 SOAP 服务获得了
我一直在网上的不同论坛上搜索答案,但似乎没有与我的情况相符的... 我正在使用 Windows 7,VS2010。 我有一个使用定时器来调用任务栏刷新功能的应用程序。在该任务栏函数中包含对 LoadI
我是一名优秀的程序员,十分优秀!