简体   繁体   中英

Google Calendar API Issue with Javascript

I'm trying to use the google Calendar API to get all events from a G-Calendar. The following code works with Node.js

const {google} = require('googleapis');

const auth = new google.auth.JWT(
    CREDENTIALS.client_email,
    null,
    CREDENTIALS.private_key,
    SCOPES
);

const getEvents = async (dateTimeStart, dateTimeEnd) => {

    try {
        let response = await calendar.events.list({
            auth: auth,
            calendarId: calendarId,
            timeMin: dateTimeStart,
            timeMax: dateTimeEnd,
            timeZone: 'Asia/Kolkata'
        });
    
        let items = response['data']['items'];
        return items;
    } catch (error) {
        console.log(`Error at getEvents --> ${error}`);
        return 0;
    }
};

But because I can't use the "require" in normal browser javascript it doesn't work. I included <script src="https://apis.google.com/js/api.js"></script> and const google = gapi; instead of the const {google} = require('googleapis');

That in itself works but it does not recognize const auth = new google.auth.JWT() as a function anymore and throws an Uncaught TypeError: google.auth is undefined

I would really appreachiate if someone could help. Thank you all in advance!

If you need a client-side implementation for "normal browser javascript", you cannot use the node.js implementation

Instead you would need to create a flow to obtain a Google service account access token. There is a good sample of how to implement it with XHR:

https://stackoverflow.com/a/29288013/11599789

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM