Как правильно аутентифицировать и использовать GoogleCalendar-API с помощью oAuth2 в среде Vue CLI - PullRequest
0 голосов
/ 12 мая 2019

Я пытаюсь интегрировать Google-Calendar-API в мое веб-приложение на основе Vue-CLI. Я решил использовать версию GoogleAPI для node.js, полученную с этого сайта: https://developers.google.com/calendar/quickstart/nodejs#troubleshooting. Однако я получил:

TypeError: Ожидается, что input будет Function или Object, получено не определен

Это для моего личного проекта, написанного на Vue-Cli, Vue Router, Vuetify.js и дополнительно аутентифицированного через Firebase (вход через учетную запись Google). После того, как пользователь войдет в систему через пользовательский интерфейс Firebase (через учетную запись Google), он получит доступ к странице панели инструментов, где он сможет получить доступ к своему календарю через систему Google oAuth2 API (застрял). Сначала я пытался использовать браузерный API javascript, но не смог (и лично предпочел версию node.js позже).

Dashboard.vue

<script>
import { config } from "@/../hidden/config.js";
const {google} = require('googleapis');

// If modifying these scopes, delete token.json.

// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = '@/assets/token.json';
export default {
  data() {
    return {
      oAuth2Client: null,
      SCOPES: ['https://www.googleapis.com/auth/calendar.readonly'],
      client_secret: "", 
      client_id: "", 
      redirect_uris: ""
    };
  },
  methods: {

    /**
     * Create an OAuth2 client with the given credentials, and then execute the
     * given callback function.
     * @param {Object} credentials The authorization client credentials.
     * @param {function} callback The callback to call with the authorized client.
     */
    authorize: () => {
      const self = this;
      self.oAuth2Client = new google.auth.OAuth2(
          client_id, client_secret, redirect_uris[0]);

      self.getAccessToken(self.oAuth2Client);
      self.oAuth2Client.setCredentials();
      self.listEvents(oAuth2Client);
    },

    /**
     * Get and store new token after prompting for user authorization, and then
     * execute the given callback with the authorized OAuth2 client.
     * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
     * @param {getEventsCallback} callback The callback for the authorized client.
     */
    getAccessToken: () => {
      const self = this;
      const authUrl = self.oAuth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: SCOPES,
      });
      console.log('Authorize this app by visiting this url:', authUrl);
      self.oAuth2Client.getToken(code, (err, token) => {
        if (err) return console.error('Error retrieving access token', err);
        self.oAuth2Client.setCredentials(token);
        // self.listEvents();
      });
    }

    /**
     * Lists the next 10 events on the user's primary calendar.
     * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
     */

     /*
    listEvents: () => {
      const self = this;
      const auth = self.oAuth2Client;
      const calendar = google.calendar({version: 'v3', auth});
      calendar.events.list({
        calendarId: 'primary',
        timeMin: (new Date()).toISOString(),
        maxResults: 10,
        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) {
          console.log('Upcoming 10 events:');
          events.map((event, i) => {
            const start = event.start.dateTime || event.start.date;
            console.log(`${start} - ${event.summary}`);
          });
        } else {
          console.log('No upcoming events found.');
        }
      });
    }
      */
  },
  created: function() {
    const {credentials} = require("@/credentials.json");
    this.client_secret = credentials.installed.client_secret;
    this.client_id = credentials.installed.client_id;
    this.redirect_uris = credentials.installed.redirect_uris;
    //this.authorize();
  }
};
</script>

Я ожидаю, что смогу подключиться к API Календаря Google и начать работать над фактическим манипулированием информацией о событиях календаря для моих целей. Однако я получаю сообщение об ошибке:

TypeError: Ожидается, что input будет Function или Object, получено undefined

. Я пытался найти людей с похожими проблемами в Интернете, однако я не нашел ни видео-руководств, ни письменных руководств для проектов Vue-cli, использующих API Google.

Признаюсь, что я немного изменил свой код из ссылочного примера с веб-сайта, чтобы избежать использования пакетов fs и readline npm. Однако в этих случаях сообщение об ошибке было таким же.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...