我正在尝试使用此处列出的https://developers.google.com/google-apps/calendar/v3/reference/freebusy/query中的NodeJS API从Google日历中获取忙碌信息。问题是我得到的唯一错误响应是“无效请求”。当我使用Google的Try It工具运行它时,我能够获得响应。我知道我正在获得授权客户。我该怎么做才能进一步解决这个问题?
function getAvail(auth, dateTimeRange, calID) {
var deferred = Q.defer(); // get a new deferral
calendar.freebusy.query({
auth: auth,
items: [{id: calID}],
timeMin: (dateTimeRange.start).toISOString(),
timeMax: (dateTimeRange.end).toISOString(),
}, function(err, response) {
console.log('Response from the Calendar service: ' + response);
if (err) {
console.log('There was an error contacting the Calendar service: ' + err);
deferred.reject(); // deferred reject here
return;
}
var events = response[calID]['busy'];
if (events.length == 0) {
console.log('No upcoming events found.');
} else {
console.log('busy in here...');
}
deferred.resolve(response); // deferred resolve here
});
return deferred.promise; // return a promise
}
答案 0 :(得分:10)
唷!我终于弄清楚我做错了什么。这是与错误的评论一起使用的代码。我希望有更好的方法来找出这个问题。
function getAvail(auth, dateTimeRange, calID) {
console.log('auth:'+JSON.stringify(auth));
console.log('date Time Range :'+(dateTimeRange.start).toISOString()+' --->'+(dateTimeRange.end).toISOString());
console.log('calendar id to check freebusy:'+calID);
var deferred = Q.defer(); // get a new deferral
calendar.freebusy.query({
auth: auth,
headers: { "content-type" : "application/json" },
resource:{items: [{"id" : calID}], //needed to include resource instead of sending the params directly.
timeMin: (dateTimeRange.start).toISOString(),
timeMax: (dateTimeRange.end).toISOString()
}
}, function(err, response) {
console.log('Response from the Calendar service: ' + JSON.stringify(response));
if (err) {
console.log('There was an error contacting the Calendar service: ' + err);
deferred.reject(); // deferred reject here
return;
}
var events = response.calendars[calID].busy;
if (events.length == 0) {
console.log('No upcoming events found.');
} else {
console.log('busy in here...');
}
deferred.resolve(response); // deferred resolve here
});
return deferred.promise; // return a promise
}
这是很多冥想,并密切关注文档。谷歌的nodejs库还没有特别好的文档记录(嗯,它仍然是alpha)。但这是freebusy的功能:
this.freebusy = {
/**
* calendar.freebusy.query
*
* @desc Returns free/busy information for a set of calendars.
*
* @alias calendar.freebusy.query
* @memberOf! calendar(v3)
*
* @param {object} params - Parameters for request
* @param {object} params.resource - Request body data** <<<< -- this is what I was missing.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
query: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/calendar/v3/freeBusy',
method: 'POST'
},
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
}
};
在循环中创建闭包还有一些额外的知识,我从这里学到了:JavaScript closure inside loops – simple practical example。如果有其他人遇到类似的问题,请告诉我。我很乐意分享我的代码示例。