Jghorton14
Jghorton14

Reputation: 764

Google Sheets Client undefined with Node

I am having trouble grabbing the sheets object in node. I am able to authenticate, but when I try to read the given sheet, client.sheets returns undefined. Which is weird because the sheets object is populated with data as shown below. Even if I pass in the the client like readSheets(gapi.client)and log the variable inside readSheets it still returns undefined. Why is this happening?

    var CLIENT_ID = 'MYID.apps.googleusercontent.com';
    var API_KEY = 'MYAPIKEY';
    var DISCOVERY_DOCS = ["https://sheets.googleapis.com/$discovery/rest?version=v4"];
    var SCOPES = "https://www.googleapis.com/auth/spreadsheets";

    gapi.load('client', {
        callback: function() {
          initClient();
        },
        onerror: function() {
          alert('gapi.client failed to load!');
        }
      });

    const initClient = () => {
        console.log(gapi.client)
        gapi.client.init({
            apiKey: API_KEY,
            clientId: CLIENT_ID,
            discoveryDocs: DISCOVERY_DOCS,
            scope: SCOPES
        });
        readSheets();
    }

    function readSheets() {
        console.log(gapi.client.sheets); // undefined
        gapi.client.sheets.spreadsheets.values.get({
            spreadsheetId: 'MySpreadsheetID',
            majorDimension: "COLUMNS",
            range: 'Sheet1!A1:B2',
        }).then(function(response) {
            console.log(response.result.values)
        }, function(response) {
            console.log('Error: ' + response.result.error.message);
        }); 
    }

gapi.client then gapi.client.sheets in the console:

enter image description here

Upvotes: 1

Views: 1134

Answers (1)

Maxim Mazurok
Maxim Mazurok

Reputation: 4162

You should not use Browser aka Client-Side aka GAPI on the backend (in NodeJS environment).

For NodeJS you should use this library - googleapis.

For Browser you should use GAPI (https://apis.google.com/js/api.js). If you want to use TypeScript with GAPI - you should install @types/gapi.client.sheets or generate typing yourself using google-api-typings-generator.

For more details about the difference between these two use-cases, refer to: JavaScript VS NodeJS Google API Clients

Upvotes: 1

Related Questions