authClient.request不是一个函数

时间:2017-05-04 21:43:40

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

我正在尝试使用Google日历api创建活动但是,我在授权方面遇到了问题。我创建了一个谷歌登录,一种不同的方式,所以我不确定连接到谷歌日历的最佳方式,这是我的hwapi文件:

var Homework = require('../models/homework');
var mongoose = require('mongoose');
var google = require('googleapis');
var jwt = require('jsonwebtoken');
var secret = 'check123';
var googleAuth = require('google-auth-library');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;


var googleAuth = require('google-auth-library');

// function authorize(credentials, callback) {
//   var clientSecret = credentials.installed.client_secret;
//   var clientId = credentials.installed.client_id;
//   var redirectUrl = credentials.installed.redirect_uris[0];

//   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);
//     }
//   });
// }
//mongoose.connect('mongodb://localhost:27017/test');
var auth = new googleAuth();


  var clientSecret = '4etHKG0Hhj84bKCBPr2YmaC-';
  var clientId = '655984940226-dqfpncns14b1uih73i7fpmot9hd16m2l.apps.googleusercontent.com';
  var redirectUrl = 'http://localhost:8000/auth/google/callback';
  var auth = new googleAuth();
  var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
    //console.log(auth);    



module.exports = function(hwRouter,passport){

    hwRouter.post('/homeworks', function(req, res){
        var homework = new Homework();
        homework.summary = req.body.summary;
        homework.description = req.body.description;
        homework.startDate = req.body.startDate;
        homework.endDate = req.body.endDate;
        if(req.body.summary == null || req.body.summary == '' || req.body.description == null || req.body.description == '' || req.body.startDate == null || req.body.startDate == '' || req.body.endDate == null || req.body.endDate == ''){
            res.send("Ensure all fields were provided!");
        }
        else{
            homework.save(function(err){
                if(err){
                    res.send('Homework already exists!');
                }
                else{
                    res.send('Homework created successfully!');
                }
            });
        }
    })


    var calendar = google.calendar('v3');
    hwRouter.get('/retrieveHW/:summary', function(req,res){
        Homework.find({},function(err,hwData){
            console.log(hwData);
            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': '2015-05-28T09:00:00-07:00', 
                'timeZone': 'America/Los_Angeles',
              },
              'end': {
                'dateTime': '2015-05-28T17:00:00-07:00',
                'timeZone': 'America/Los_Angeles',
              },
              'recurrence': [
                'RRULE:FREQ=DAILY;COUNT=2'
              ],
              'attendees': [
                {'email': 'lpage@example.com'},
                {'email': 'sbrin@example.com'},
              ],
              'reminders': {
                'useDefault': false,
                'overrides': [
                  {'method': 'email', 'minutes': 24 * 60},
                  {'method': 'popup', 'minutes': 10},
                ],
              },
            };

console.log(auth)
        calendar.events.insert({

          auth: auth,
          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);
        });

            res.json({success: true, message: "successfull retrieved the homework!"});
        }); 

    })

    return hwRouter;
}

正如你所看到的,我已经尝试使用goog api提供的一些代码来确保我可以连接到它。我的代码被卡住的部分是我相信当我在calendar.event.create部分中传递auth:auth时。它给了我错误:authClient.request不是一个函数。任何建议都会有所帮助!

1 个答案:

答案 0 :(得分:0)

尝试关注JavaScript示例:

/**
       *  Initializes the API client library and sets up sign-in state
       *  listeners.
       */
      function initClient() {
        gapi.client.init({
          discoveryDocs: DISCOVERY_DOCS,
          clientId: CLIENT_ID,
          scope: SCOPES
        }).then(function () {
          // Listen for sign-in state changes.
          gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

          // Handle the initial sign-in state.
          updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
          authorizeButton.onclick = handleAuthClick;
          signoutButton.onclick = handleSignoutClick;
        });
      }

      /**
       *  Called when the signed in status changes, to update the UI
       *  appropriately. After a sign-in, the API is called.
       */
      function updateSigninStatus(isSignedIn) {
        if (isSignedIn) {
          authorizeButton.style.display = 'none';
          signoutButton.style.display = 'block';
          listUpcomingEvents();
        } else {
          authorizeButton.style.display = 'block';
          signoutButton.style.display = 'none';
        }
      }

在此代码中,initClient()运行后,gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);会侦听任何状态更改。如果updateSigninStatus成功登录,initClient()函数将处理。如果是,则调用listUpcomingEvents()函数,在您的情况下,您将调用创建事件函数。

这是一个related SO post,它可以帮助您实现JS客户端库代码实现。

希望这有帮助。