Guida rapida per Node.js

Le guide rapide spiegano come configurare ed eseguire un'app che chiama un'API Google Workspace.

Le guide rapide di Google Workspace utilizzano le librerie client API per gestire alcuni dettagli del flusso di autenticazione e autorizzazione. Ti consigliamo di utilizzare le librerie client per le tue app. Questa guida rapida utilizza un approccio di autenticazione semplificato, appropriato per un ambiente di test. Per un ambiente di produzione, consigliamo di consultare l'autenticazione e l'autorizzazione prima di scegliere le credenziali di accesso appropriate per la tua app.

Creare un'applicazione a riga di comando Node.js che invia richieste all'API Drive Etichette.

Obiettivi

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

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 Etichette.

    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 Google Cloud, vai a Menu > API e servizi > Credenziali.

    Vai a credenziali

  2. Fai clic su Crea credenziali > ID client OAuth.
  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 Google Cloud.
  5. Fai clic su Crea. Viene visualizzata la schermata di creazione del client OAuth, che mostra il nuovo ID client e il nuovo client secret.
  6. Fai clic su Ok. Le credenziali appena create vengono visualizzate nella sezione ID client OAuth 2.0.
  7. Salva il file JSON scaricato come credentials.json e spostalo 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 l'esempio

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

  2. Incolla il codice seguente nel file:

        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 l'esempio

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

    node .
    
  2. La prima volta che esegui l'esempio, ti verrà 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, selezionane uno da utilizzare per l'autorizzazione.
    2. Fai clic su Accept (accetta).

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

Hai creato la tua prima applicazione Nodejs che invia richieste all'API Drive Etichette.

Passaggi successivi