authClient.request не является функцией

Я пытаюсь создать события, используя API календаря Google, но у меня проблемы с авторизацией. Я создал логин Google, другой способ, поэтому я не уверен, что лучший способ подключиться к календарю Google, это мой файл 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;
}

Как вы можете видеть, я пытался использовать некоторый код, предоставленный API goog, просто чтобы убедиться, что я могу к нему подключиться. Часть, в которой застрял мой код, - это, я полагаю, когда я передаю его auth: auth в части calendar.event.create. это дает мне ошибку: authClient.request не является функцией. Любой совет поможет спасибо!

1 ответ

Попробуйте следовать примеру 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() функция, в вашем случае вы будете вызывать функцию создания события.

Вот соответствующий пост SO, который может помочь вам с реализацией кода клиентской библиотеки JS.

Надеюсь это поможет.

Другие вопросы по тегам