googleapis TypeError:authClient.request不是nodejs中的函数

时间:2017-03-17 09:22:07

标签: javascript node.js google-api google-calendar-api google-authentication

我正在使用googleapisgoogle auth用于Google日历。我已经获取calendar event列表,但是当我尝试插入事件时,它会抛出一个错误,即TypeError: authClient.request is not a function in nodejs.

这是我的代码段: -

// route.js

...
app.get('/auth/google', passport.authenticate('google', {
        scope: ['profile', 'email', 'https://www.googleapis.com/auth/calendar']
    }));
...

//服务器/ passport.js

... 
var google = require('googleapis');
var googleAuth = require('google-auth-library');
...
 passport.use(new GoogleStrategy({
            clientID: configAuth.googleAuth.clientID,
            clientSecret: configAuth.googleAuth.clientSecret,
            callbackURL: configAuth.googleAuth.callbackURL,
            passReqToCallback: true
        },
        function(req, token, refreshToken, profile, done) {
...
var clientSecret = configAuth.googleAuth.clientSecret;
var clientId = configAuth.googleAuth.clientID;
var redirectUrl = configAuth.googleAuth.callbackURL;
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
var tokenObj = { access_token: token, refresh_token: refreshToken }
                            oauth2Client.credentials = tokenObj;

req.session.oauth2Client = oauth2Client;


var calendar = google.calendar('v3');
 calendar.events.list({
     auth: oauth2Client,
     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;
     var googleEvents = [];
     if (events.length == 0) {
        console.log('No upcoming events found.');
    } else {
        for (var i = 0; i < events.length; i++) {
           var temp = {};
           temp.info = events[i].summary;
           temp.start = events[i].start.dateTime || events[i].start.date;
           googleEvents.push(temp);
         }
     }
     console.log(googleEvents); // it is work fine
 });
...
...
}))

//服务器/控制器/ todo.js

....
....
var event = {
                'summary': 'Google I/O 2015',
                'location': '800 Howard St., San Francisco, CA 94103',
                'description': 'A chance to hear more about Google\'s developer products.',
                'start': {
                    'dateTime': '2017-03-20T09:00:00-07:00',
                    'timeZone': 'America/Los_Angeles',
                },
                'end': {
                    'dateTime': '2017-03-23T17:00:00-07:00',
                    'timeZone': 'America/Los_Angeles',
                },
                'recurrence': [
                    'RRULE:FREQ=DAILY;COUNT=2'
                ],
                'reminders': {
                    'useDefault': false,
                    'overrides': [
                        { 'method': 'email', 'minutes': 24 * 60 },
                        { 'method': 'popup', 'minutes': 10 },
                    ],
                },
            };


var calendar = google.calendar('v3');
calendar.events.insert({     //here ERROR 'TypeError: authClient.request is not a function' is  generated
    auth: req.session.oauth2Client,
    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);
});

...
...

1 个答案:

答案 0 :(得分:3)

这不起作用,因为req.session存储为json:

  

要存储或访问会话数据,只需使用request属性即可   req.session,由商店(通常)序列化为JSON,所以   嵌套对象通常很好。   https://github.com/expressjs/session

当存储为json时,所有方法都从对象中剥离,只保存数据。

我通过创建一个包含所有oauth对象的单独的全局对象来解决它,可以通过会话ID检索:

//Global object
var auths = {};

//...

//Save Client
auths[req.session.id] = oauth2Client;

//...

//use client
var calendar = google.calendar('v3');
calendar.events.insert({    
  auth: auths[req.session.id],
  calendarId: 'primary',