Guida rapida per Node.js

Le guide rapide spiegano come configurare ed eseguire un'app che chiama un'API Google Workspace. Questa guida rapida utilizza un approccio di autenticazione semplificato, adatto a un ambiente di test. Per un ambiente di produzione, ti consigliamo di scoprire di più sull'autenticazione e sull'autorizzazione prima di scegliere le credenziali di accesso appropriate per la tua app.

Crea un'applicazione a riga di comando Node.js che effettua richieste all'API Drive Labels.

Obiettivi

  • Configurare l'ambiente.
  • Installare la libreria client.
  • Configurare l'esempio.
  • Eseguire l'esempio.

Prerequisiti

  • Un Account Google.

Configurare l'ambiente

Per completare questa guida rapida, configura l'ambiente.

Abilitare l'API

Prima di utilizzare le API di Google, devi attivarle in un progetto Google Cloud. Puoi attivare una o più API in un singolo progetto Google Cloud.
  • Nella console Google Cloud, abilita l'API Drive Labels.

    Abilita l'API

Autorizzare le credenziali per un'applicazione desktop

Per autenticare gli utenti finali e accedere ai dati utente nella tua app, devi creare uno o più ID client OAuth 2.0. L'ID client viene utilizzato per identificare una singola app nei server OAuth di Google. Se l'app viene eseguita su più piattaforme, devi creare un ID client separato per ogni piattaforma.
  1. Nella console API di Google, vai a Menu > Piattaforma di autenticazione Google > Client.

    Vai a Client

  2. Fai clic su Crea client.
  3. Fai clic su Tipo di applicazione > App desktop.
  4. Nel campo Nome, digita un nome per la credenziale. Questo nome viene visualizzato solo nella console API di Google.
  5. Fai clic su Crea.

    La credenziale appena creata viene visualizzata in "ID client OAuth 2.0".

  6. Salva il file JSON scaricato come credentials.json e sposta il file nella directory di lavoro.

Installare la libreria client

  • Installa le librerie utilizzando npm:

    npm install googleapis@113 @google-cloud/local-auth@2.1.1 --save
    

Configurare l'esempio

  1. Nella directory di lavoro, crea un file denominato index.js.

  2. Nel file, incolla il seguente codice:

        const fs = require('fs');
        const readline = require('readline');
        const {google} = require('googleapis');
    
        // If modifying these scopes, delete token.json.
        const SCOPES = ['https://www.googleapis.com/auth/drive.labels.readonly'];
        // 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 = 'token.json';
    
        // Load client secrets from a local file.
        fs.readFile('credentials.json', (err, content) => {
          if (err) return console.log('Error loading client secret file:', err);
          // Authorize a client with credentials, then call the Google Drive Labels
          // API.
          authorize(JSON.parse(content), listDriveLabels);
        });
    
        /**
        * 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.
        */
        function authorize(credentials, callback) {
          const {client_secret, client_id, redirect_uris} = credentials.installed;
          const oAuth2Client = new google.auth.OAuth2(
              client_id, client_secret, redirect_uris[0]);
    
          // Check if we have previously stored a token.
          fs.readFile(TOKEN_PATH, (err, token) => {
            if (err) return getNewToken(oAuth2Client, callback);
            oAuth2Client.setCredentials(JSON.parse(token));
            callback(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.
        */
        function getNewToken(oAuth2Client, callback) {
          const authUrl = oAuth2Client.generateAuthUrl({
            access_type: 'offline',
            scope: SCOPES,
          });
          console.log('Authorize this app by visiting this url:', authUrl);
          const rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout,
          });
          rl.question('Enter the code from that page here: ', (code) => {
            rl.close();
            oAuth2Client.getToken(code, (err, token) => {
              if (err) return console.error('Error retrieving access token', err);
              oAuth2Client.setCredentials(token);
              // Store the token to disk for later program executions
              fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
                if (err) return console.error(err);
                console.log('Token stored to', TOKEN_PATH);
              });
              callback(oAuth2Client);
            });
          });
        }
    
        function listDriveLabels(auth) {
          const service = google.drivelabels({version: 'v2', auth});
          const params = {
            'view': 'LABEL_VIEW_FULL'
          };
          service.labels.list(params, (err, res) => {
            if (err) return console.error('The API returned an error: ' + err);
            const labels = res.data.labels;
            if (labels) {
              labels.forEach((label) => {
                const name = label.name;
                const title = label.properties.title;
                console.log(`${name}\t${title}`);
              });
            } else {
              console.log('No Labels');
            }
          });
        }
    

Eseguire l'esempio

  1. Nella directory di lavoro, esegui l'esempio:

    node .
    
  2. La prima volta che esegui l'esempio, ti viene chiesto di autorizzare l'accesso:

    1. Se non hai ancora eseguito l'accesso al tuo Account Google, ti verrà chiesto di farlo. Se hai eseguito l'accesso a più account, seleziona un account da utilizzare per l'autorizzazione.
    2. Fai clic su Accetto.

    Le informazioni di autorizzazione vengono archiviate nel file system, quindi la volta successiva che esegui il codice campione non ti verrà richiesta l'autorizzazione.

Hai creato correttamente la tua prima applicazione Nodejs che effettua richieste all'API Drive Labels.

Passaggi successivi