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ù su autenticazione e autorizzazione prima di scegliere le credenziali di accesso adatte alla tua app.

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

Obiettivi

  • Configurare l'ambiente.
  • Installa la libreria client.
  • Configura il campione.
  • Esegui il campione.

Prerequisiti

  • Un Account Google.

Configura l'ambiente

Per completare questa guida rapida, configura il tuo ambiente.

Abilita 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 ciascuna piattaforma.
  1. Nella console Google Cloud, vai a Menu > Google Auth platform > Client.

    Vai a Clienti

  2. Fai clic su Crea cliente.
  3. Fai clic su Tipo di applicazione > App per computer.
  4. Nel campo Nome, digita un nome per la credenziale. Questo nome viene visualizzato solo nella console Google Cloud.
  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.

installa la libreria client

  • Installa le librerie utilizzando npm:

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

Configura il campione

  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');
            }
          });
        }
    

Esegui il campione

  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 in cui esegui il codice campione, non ti viene chiesto di autorizzare.

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

Passaggi successivi