Sobes.tech
Junior

Welke tools gebruikt u om met de server te communiceren?

sobes.tech AI

Antwoord van AI

  • XMLHttpRequest (XHR):

    const xhr = new XMLHttpRequest();
    xhr.open('GET', '/api/data', true); // Instelling van het verzoek
    xhr.onload = function() {
      if (xhr.status >= 200 && xhr.status < 400) {
        const data = JSON.parse(xhr.responseText); // Verwerking van succesvolle reactie
        console.log(data);
      } else {
        // Foutafhandeling
        console.error('Fout bij verzoek:', xhr.status);
      }
    };
    xhr.onerror = function() {
      // Netwerkfouten afhandelen
      console.error('Netwerkfout');
    };
    xhr.send(); // Verzoek verzenden
    
  • Fetch API:

    fetch('/api/data')
      .then(response => {
        if (!response.ok) {
          throw new Error('HTTP status ' + response.status); // HTTP-foutafhandeling
        }
        return response.json(); // JSON-parsering
      })
      .then(data => {
        console.log(data); // Gegevensverwerking
      })
      .catch(error => {
        console.error('Fout bij verzoek:', error); // Andere fouten afhandelen
      });
    
  • Bibliotheken gebaseerd op Fetch of XHR:

    • Axios:
      // Installatie van Axios: npm install axios
      
      import axios from 'axios';
      
      axios.get('/api/data')
        .then(response => {
          console.log(response.data); // Toegang tot gegevens via .data
        })
        .catch(error => {
          console.error('Fout bij verzoek:', error); // Foutafhandeling
        });
      
    • jQuery.ajax: (Indien jQuery wordt gebruikt)
      // jQuery-bibliotheek is vereist
      
      $.ajax({
        url: '/api/data',
        method: 'GET',
        dataType: 'json', // Verwacht datatype
        success: function(data) {
          console.log(data); // Verwerking van succesvolle reactie
        },
        error: function(jqXHR, textStatus, errorThrown) {
          console.error('Fout bij verzoek:', textStatus, errorThrown); // Foutafhandeling
        }
      });
      
  • WebSockets: Voor bidirectionele communicatie in realtime.

    const socket = new WebSocket('ws://localhost:8080'); // Verbinding maken met WebSocket-server
    
    socket.onopen = function(event) {
      console.log('WebSocket verbonden'); // Verbindingsevent
      socket.send('Hallo van de client!'); // Bericht verzenden
    };
    
    socket.onmessage = function(event) {
      console.log('Bericht van de server:', event.data); // Bericht ontvangen
    };
    
    socket.onerror = function(event) {
      console.error('WebSocket-fout:', event); // Foutgebeurtenis
    };
    
    socket.onclose = function(event) {
      if (event.wasClean) {
        console.log('Verbinding netjes gesloten, code=' + event.code + ' reden=' + event.reason);
      } else {
        console.error('Verbinding verbroken'); // Bijvoorbeeld, serverproces is beëindigd
      }
    };
    
    // Verbinding sluiten
    // socket.close();