Sobes.tech
Junior

Quali strumenti utilizzi per interagire con il server?

sobes.tech AI

Risposta dell'AI

  • XMLHttpRequest (XHR):

    const xhr = new XMLHttpRequest();
    xhr.open('GET', '/api/data', true); // Configurazione della richiesta
    xhr.onload = function() {
      if (xhr.status >= 200 && xhr.status < 400) {
        const data = JSON.parse(xhr.responseText); // Elaborazione risposta riuscita
        console.log(data);
      } else {
        // Gestione degli errori
        console.error('Errore nella richiesta:', xhr.status);
      }
    };
    xhr.onerror = function() {
      // Gestione errori di rete
      console.error('Errore di rete');
    };
    xhr.send(); // Invio richiesta
    
  • Fetch API:

    fetch('/api/data')
      .then(response => {
        if (!response.ok) {
          throw new Error('Stato HTTP ' + response.status); // Gestione errori HTTP
        }
        return response.json(); // Parsing JSON
      })
      .then(data => {
        console.log(data); // Gestione dati
      })
      .catch(error => {
        console.error('Errore nella richiesta:', error); // Gestione altri errori
      });
    
  • Librerie basate su Fetch o XHR:

    • Axios:
      // Installazione di Axios: npm install axios
      
      import axios from 'axios';
      
      axios.get('/api/data')
        .then(response => {
          console.log(response.data); // Accesso ai dati tramite .data
        })
        .catch(error => {
          console.error('Errore nella richiesta:', error); // Gestione errori
        });
      
    • jQuery.ajax: (Se si usa jQuery)
      // È richiesta la libreria jQuery
      
      $.ajax({
        url: '/api/data',
        method: 'GET',
        dataType: 'json', // Tipo di dati atteso
        success: function(data) {
          console.log(data); // Gestione risposta riuscita
        },
        error: function(jqXHR, textStatus, errorThrown) {
          console.error('Errore nella richiesta:', textStatus, errorThrown); // Gestione errori
        }
      });
      
  • WebSockets: Per comunicazione bidirezionale in tempo reale.

    const socket = new WebSocket('ws://localhost:8080'); // Connessione al server WebSocket
    
    socket.onopen = function(event) {
      console.log('WebSocket connesso'); // Evento di connessione
      socket.send('Ciao dal client!'); // Invio di un messaggio
    };
    
    socket.onmessage = function(event) {
      console.log('Messaggio ricevuto dal server:', event.data); // Ricezione del messaggio
    };
    
    socket.onerror = function(event) {
      console.error('Errore WebSocket:', event); // Evento di errore
    };
    
    socket.onclose = function(event) {
      if (event.wasClean) {
        console.log('Connessione chiusa pulitamente, codice=' + event.code + ' motivo=' + event.reason);
      } else {
        console.error('Connessione interrotta'); // Ad esempio, il processo del server è stato ucciso
      }
    };
    
    // Chiusura della connessione
    // socket.close();