Sobes.tech
Junior

Sunucu ile etkileşim kurmak için hangi araçları kullanıyorsunuz?

sobes.tech yapay zeka

AI'dan gelen yanıt

  • XMLHttpRequest (XHR):

    const xhr = new XMLHttpRequest();
    xhr.open('GET', '/api/data', true); // İstek ayarları
    xhr.onload = function() {
      if (xhr.status >= 200 && xhr.status < 400) {
        const data = JSON.parse(xhr.responseText); // Başarılı yanıt işleme
        console.log(data);
      } else {
        // Hata işleme
        console.error('İstek hatası:', xhr.status);
      }
    };
    xhr.onerror = function() {
      // Ağ hatası işleme
      console.error('Ağ hatası');
    };
    xhr.send(); // İstek gönder
    
  • Fetch API:

    fetch('/api/data')
      .then(response => {
        if (!response.ok) {
          throw new Error('HTTP durumu ' + response.status); // HTTP hatası işleme
        }
        return response.json(); // JSON ayrıştırma
      })
      .then(data => {
        console.log(data); // Veri işleme
      })
      .catch(error => {
        console.error('İstek hatası:', error); // Diğer hataları işleme
      });
    
  • Fetch veya XHR tabanlı kütüphaneler:

    • Axios:
      // Axios kurulumu: npm install axios
      
      import axios from 'axios';
      
      axios.get('/api/data')
        .then(response => {
          console.log(response.data); // .data ile verilere erişim
        })
        .catch(error => {
          console.error('İstek hatası:', error); // Hata işleme
        });
      
    • jQuery.ajax: (jQuery kullanılıyorsa)
      // jQuery kütüphanesi gereklidir
      
      $.ajax({
        url: '/api/data',
        method: 'GET',
        dataType: 'json', // Beklenen veri tipi
        success: function(data) {
          console.log(data); // Başarılı yanıt işleme
        },
        error: function(jqXHR, textStatus, errorThrown) {
          console.error('İstek hatası:', textStatus, errorThrown); // Hata işleme
        }
      });
      
  • WebSockets: Gerçek zamanlı çift yönlü iletişim için.

    const socket = new WebSocket('ws://localhost:8080'); // WebSocket sunucusuna bağlanma
    
    socket.onopen = function(event) {
      console.log('WebSocket bağlı'); // Bağlantı olayı
      socket.send('Sunucudan merhaba!'); // Mesaj gönder
    };
    
    socket.onmessage = function(event) {
      console.log('Sunucudan alınan mesaj:', event.data); // Mesaj alma
    };
    
    socket.onerror = function(event) {
      console.error('WebSocket hatası:', event); // Hata olayı
    };
    
    socket.onclose = function(event) {
      if (event.wasClean) {
        console.log('Temiz şekilde kapandı, kod=' + event.code + ' neden=' + event.reason);
      } else {
        console.error('Bağlantı kesildi'); // Örneğin, sunucu işlemi sonlandırıldı
      }
    };
    
    // Bağlantıyı kapat
    // socket.close();