Panduan JavaScript Fetch API: GET, POST, Penanganan Kesalahan, dan Contoh Dunia Nyata

1. Pendahuluan

JavaScript adalah salah satu bahasa pemrograman yang paling banyak digunakan dalam pengembangan web. Di antara banyak fiturnya, Fetch API telah menarik perhatian sebagai kemampuan penting untuk memungkinkan komunikasi asynchronous.

Dalam artikel ini, kami menjelaskan Fetch API secara detail—dari dasar hingga penggunaan yang lebih lanjutan. Dengan memahaminya, Anda akan dapat mengimplementasikan pengambilan data dan komunikasi server dengan lebih lancar dalam aplikasi web.

Apa itu komunikasi asynchronous?

Komunikasi asynchronous adalah metode pertukaran data dengan server sambil melanjutkan proses lain tanpa memblokir hingga komunikasi selesai. Ini meningkatkan responsivitas antarmuka pengguna dan memudahkan penanganan data tanpa frustrasi.

Misalnya, ketika pengguna mengklik tombol pada halaman web untuk mengambil data, tugas lain dapat terus berjalan tanpa menunggu respons server, yang secara signifikan meningkatkan pengalaman pengguna.

Apa itu Fetch API?

Fetch API adalah antarmuka modern untuk melakukan komunikasi asynchronous dalam JavaScript. Ia diperkenalkan sebagai alternatif untuk XMLHttpRequest (XHR) tradisional, menawarkan sintaks yang ringkas dan konfigurasi yang fleksibel.

Dengan API ini, Anda dapat dengan mudah menulis logika untuk mengambil data dari server atau mengirim data ke server.

Pada bagian berikutnya, kami akan memperkenalkan semuanya langkah demi langkah—dari penggunaan dasar Fetch API hingga contoh praktis dunia nyata.

2. Apa itu Fetch API?

Fetch API adalah antarmuka standar terbaru untuk melakukan komunikasi asynchronous dalam JavaScript. Pada bagian ini, kami menjelaskan peran dasarnya dan bagaimana ia berbeda dari pendekatan tradisional.

Gambaran Umum Fetch API

Fetch API dirancang untuk mengambil sumber daya melalui jaringan.
Ini memudahkan aplikasi web berkomunikasi dengan server.

Fitur utama

  • Berbasis Promise : Tidak perlu mengandalkan fungsi callback, memungkinkan Anda menulis kode yang lebih mudah dibaca.
  • Sintaks ringkas : Dibandingkan dengan XMLHttpRequest, dapat secara signifikan mengurangi jumlah kode.
  • Fleksibilitas tinggi : Anda dapat menyesuaikan permintaan dan respons secara detail.
  • Desain modern : Bekerja dengan baik bersama fitur JavaScript modern, memungkinkan kode yang dapat dipelihara.

Berikut adalah contoh dasar penggunaan Fetch API.

fetch('https://api.example.com/data')
  .then(response => response.json()) // Convert to JSON
  .then(data => console.log(data))  // Output the data
  .catch(error => console.error('Error:', error)); // Error handling

Kode ini mengambil data dari URL yang ditentukan, mengubahnya menjadi JSON, dan menampilkannya di konsol. Jika terjadi error, ia mencetak pesan error.

Perbedaan dengan XMLHttpRequest tradisional

Fetch API adalah pendekatan baru yang menggantikan XMLHttpRequest (XHR) yang banyak digunakan. Tabel di bawah membandingkan keduanya.

FeatureFetch APIXMLHttpRequest
Code simplicityConcise, readable syntaxOften complex with many callbacks
Asynchronous handlingSupports Promises and offers high flexibilityRequires callback functions
Stream processingNative supportRequires additional handling
Working with JSONEasy to handleRequires explicit parsing
Error handlingFlexible and can be centralizedOften becomes complex

Seperti yang Anda lihat, Fetch API menarik karena desainnya yang ringkas dan modern. Khususnya, berbasis Promise memungkinkan Anda menulis logika asynchronous secara lebih alami.

Ringkasan

Fetch API adalah alat yang kuat dan mudah digunakan untuk komunikasi asynchronous dalam JavaScript. Karena lebih sederhana diimplementasikan dibandingkan XHR tradisional, ia menjadi keterampilan penting untuk pengembangan web modern.

Pada bagian berikutnya, kami akan membahas pola penggunaan konkret Fetch API dengan contoh kode.

3. Penggunaan Dasar Fetch API

Pada bagian ini, kami menjelaskan penggunaan dasar Fetch API dengan contoh kode konkret. Kami terutama membahas poin-poin berikut.

  • Sintaks metode fetch() dan contoh dasar
  • Cara mengimplementasikan permintaan GET
  • Cara menangani data respons

Sintaks dasar metode fetch()

Dengan Fetch API, Anda mengirim permintaan ke server menggunakan metode fetch(). Berikut adalah sintaks dasarnya.

fetch(url, options)
  .then(response => {
    // Handle the response
  })
  .catch(error => {
    // Handle errors
  });

Argumen

  • url : URL tempat permintaan dikirim.
  • options (opsional): Pengaturan opsi yang mencakup method, headers, body, dan lainnya.

Nilai Kembali

  • Objek Promise : Mengembalikan hasil dari proses asinkronus.

Cara mengimplementasikan permintaan GET

Penggunaan paling dasar dari Fetch API adalah permintaan GET, yang mengambil data dari server.

Contoh: Mengambil data JSON

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network error');
    }
    return response.json(); // Retrieve data as JSON
  })
  .then(data => {
    console.log(data); // Display the retrieved data
  })
  .catch(error => {
    console.error('Error:', error); // Print an error log
  });

Cara memproses data respons

Dengan Fetch API, Anda dapat memproses data respons dalam berbagai format. Berikut adalah contoh umum.

  1. Mengambil data teks
    fetch('https://example.com/data.txt')
      .then(response => response.text()) // Retrieve data as text
      .then(data => console.log(data))
      .catch(error => console.error('Error:', error));
    
  1. Mengambil data biner
    fetch('https://example.com/image.jpg')
      .then(response => response.blob()) // Retrieve as binary data
      .then(blob => {
        const imgURL = URL.createObjectURL(blob);
        document.querySelector('img').src = imgURL;
      })
      .catch(error => console.error('Error:', error));
    
  1. Mengambil informasi header
    fetch('https://example.com/api')
      .then(response => {
        console.log(response.headers.get('Content-Type')); // Get a header value
      })
      .catch(error => console.error('Error:', error));
    

Ringkasan

Di sini, kami membahas permintaan GET dasar menggunakan Fetch API dan cara menangani respons.

Fetch API adalah alat yang fleksibel yang memudahkan pengambilan berbagai jenis data, seperti teks, JSON, dan data biner. Setelah memahami dasar-dasar ini, akan lebih mudah menerapkannya pada bab selanjutnya, termasuk penanganan kesalahan dan permintaan POST.

Di bagian selanjutnya, kami akan menjelaskan penanganan kesalahan dengan Fetch API secara detail.

4. Penanganan Kesalahan

Di bagian ini, kami menjelaskan penanganan kesalahan saat menggunakan Fetch API. Saat berkomunikasi dengan server, berbagai masalah dapat terjadi, seperti kesalahan jaringan dan kesalahan respons. Menangani ini dengan benar dapat meningkatkan pengalaman pengguna.

Dasar-dasar Penanganan Kesalahan

Dengan Fetch API, Anda dapat menggunakan metode catch() untuk menangani kasus seperti kegagalan jaringan atau respons kesalahan.

Contoh penanganan kesalahan dasar

fetch('https://example.com/data')
  .then(response => {
    if (!response.ok) { // Check the response status code
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('An error occurred:', error)); // Error handling

Penanganan Kesalahan dengan try…catch

Menggunakan Async/Await memungkinkan Anda menulis kode yang lebih bersih dan mudah dibaca. Dalam hal ini, Anda menangani kesalahan dengan pernyataan try...catch.

Contoh: Penanganan Kesalahan dengan Async/Await

async function fetchData() {
  try {
    const response = await fetch('https://example.com/data');
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('An error occurred:', error);
  }
}

fetchData();

Mengimplementasikan Timeouts

Fetch API tidak menyertakan fitur timeout bawaan secara default. Namun, mengimplementasikan timeout memungkinkan Anda menangani respons lambat dengan tepat.

Contoh: Mengimplementasikan Timeout

function fetchWithTimeout(url, timeout = 5000) {
  return Promise.race([
    fetch(url),
    new Promise((_, reject) =>
      setTimeout(() => reject(new Error('Request timed out')), timeout)
    ),
  ]);
}

fetchWithTimeout('https://example.com/data', 5000)
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('An error occurred:', error));

Detecting network errors

A network error refers to cases where the server cannot be reached or the connection is interrupted. With the Fetch API, these errors can also be detected with catch().

Example: Handling a network error

fetch('https://invalid-url.com/data')
  .then(response => response.json())
  .catch(error => console.error('Network error:', error.message));

Summary

In this section, we introduced error handling with the Fetch API, from basics to more advanced patterns.

Key takeaways

  • Check response status codes and implement error handling
  • Simplify error handling with Async/Await
  • Handle slow responses by implementing timeouts

Error handling is critical for improving the user experience. In the next section, we’ll explain POST requests for sending data to a server.

5. Sending POST requests

In this section, we explain how to send POST requests with the Fetch API to send data to a server. We’ll cover practical examples such as sending form data and JSON.

Basic syntax for POST requests

You can implement a POST request in the Fetch API by providing an options object as the second argument to the fetch() method.

Basic syntax

fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Example: Sending JSON data

Below is an example of sending user information in JSON format.

const userData = {
  name: 'Taro Yamada',
  email: 'yamada@example.com',
};

fetch('https://example.com/api/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(userData),
})
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));

Example: Sending form data

To send form data, use the FormData object.

const formData = new FormData();
formData.append('username', 'yamada');
formData.append('file', fileInput.files[0]);

fetch('https://example.com/upload', {
  method: 'POST',
  body: formData,
})
  .then(response => response.json())
  .then(data => console.log('Upload success:', data))
  .catch(error => console.error('Error:', error));

Example: Requests with authentication information

When sending data along with authentication information (for example, a token), add the auth data to the request headers.

fetch('https://example.com/api/protected', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
  },
  body: JSON.stringify({ message: 'Hello!' }),
})
  .then(response => response.json())
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));

Error handling for POST requests

For POST requests, you can add error handling like the following to deal with network issues or server-side problems.

async function postData(url, data) {
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const result = await response.json();
    console.log('Success:', result);
  } catch (error) {
    console.error('An error occurred:', error.message);
  }
}

postData('https://example.com/api/messages', { text: 'Hello!' });

Summary

In this section, we explained the basics and practical usage of POST requests using the Fetch API.

Key takeaways

  1. How to send JSON data and form data
  2. How to implement requests with authentication information
  3. How to strengthen error handling

POST requests are essential for two-way communication with servers. In the next section, we’ll explain customization options for the Fetch API in detail.

6. Other option settings

In this section, we explain various option settings you can specify as the second argument to the Fetch API. By using these, you can easily customize requests and manage authentication information.

Basic option syntax

Fetch API options are specified as an object in the second argument.

fetch(url, {
  method: 'GET',              
  headers: {                  
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
  },
  body: JSON.stringify(data), 
  credentials: 'include',     
  mode: 'cors',               
  cache: 'no-cache',          
  redirect: 'follow',         
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Details of each option

  1. method (HTTP method)
  • Specifies the HTTP method (for example: GET, POST, PUT, DELETE).
  • The default is GET .
  1. headers (headers)
  • Specifies request headers.
  • Used to define the data format or add authentication information.
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
    }
    
  1. body (sending data)
  • Used to send data to the server with POST or PUT methods.
  1. credentials (managing credentials)
  • Controls whether credentials (cookies or HTTP authentication data) are sent.
ValueDescription
omitDo not send credentials (default)
same-originSend credentials only for same-origin requests
includeSend credentials even for cross-origin requests
  1. mode (CORS policy)
  • Controls cross-origin request behavior.
ValueDescription
corsAllow cross-origin requests (default)
no-corsAllow only simple requests (limited)
same-originAllow requests only to the same origin
  1. cache (cache control)
  • Controls how request caching is used.
ValueDescription
defaultUse the browser’s default cache settings
no-storeDo not use cache; always make a new request
reloadIgnore cache and make a new request
  1. redirect (redirect handling)
  • Specifies how redirects are handled.
ValueDescription
followAutomatically follow redirects (default)
errorTreat redirects as errors
manualHandle redirects manually (controllable in code)

Advanced customization example

Below is an example that combines multiple options.

fetch('https://example.com/api/resource', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
  },
  body: JSON.stringify({ message: 'Hello!' }),
  credentials: 'include',
  mode: 'cors',
  cache: 'no-cache',
  redirect: 'follow',
})
  .then(response => response.json())
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));

Summary

In this section, we explained various Fetch API option settings in detail.

Key takeaways

  1. How to customize headers and credentials
  2. Fine-grained settings such as CORS and cache control
  3. Advanced patterns for redirects and error handling

In the next section, we’ll introduce concrete examples of how to use the Fetch API in practice.

7. Practical examples of using the Fetch API

In this section, we explain how you can use the Fetch API in real projects with concrete examples. Through practical scenarios, you’ll build real-world Fetch API skills.

Displaying a list of API data

A common use case in web applications is fetching data from an external API and displaying it as a list. In the example below, we fetch post data from the JSONPlaceholder API and display it as an HTML list.

Code example

const url = 'https://jsonplaceholder.typicode.com/posts';

fetch(url)
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(posts => {
    const list = document.getElementById('post-list');
    posts.forEach(post => {
      const listItem = document.createElement('li');
      listItem.textContent = `${post.id}: ${post.title}`;
      list.appendChild(listItem);
    });
  })
  .catch(error => console.error('Kesalahan:', error));

HTML example

<ul id="post-list"></ul>

Submitting a form and registering data

This is an example of registering data from a form input to a server.

Code example

const form = document.getElementById('user-form');
form.addEventListener('submit', async (e) => {
  e.preventDefault();

  const formData = {
    name: document.getElementById('name').value,
    email: document.getElementById('email').value,
  };

  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/users', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(formData),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const result = await response.json();
    console.log('Pendaftaran berhasil:', result);
    alert('Pengguna telah terdaftar!');
  } catch (error) {
    console.error('Kesalahan:', error);
    alert('Terjadi kesalahan.');
  }
});

HTML example

<form id="user-form">
  <input type="text" id="name" placeholder="Nama" required />
  <input type="email" id="email" placeholder="Alamat email" required />
  <button type="submit">Daftar</button>
</form>

File upload

The Fetch API can also handle file uploads. Below is an example of uploading an image file to a server.

Code example

const fileInput = document.getElementById('file-input');
const uploadButton = document.getElementById('upload-button');

uploadButton.addEventListener('click', async () => {
  const file = fileInput.files[0];
  const formData = new FormData();
  formData.append('file', file);

  try {
    const response = await fetch('https://example.com/upload', {
      method: 'POST',
      body: formData,
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const result = await response.json();
    console.log('Unggahan berhasil:', result);
    alert('File telah diunggah!');
  } catch (error) {
    console.error('Kesalahan:', error);
    alert('Unggahan gagal.');
  }
});

HTML example

<input type="file" id="file-input" />
<button id="upload-button">Unggah</button>

Summary

In this section, we introduced practical examples using the Fetch API.

Key takeaways

  1. Creating a dynamic list by displaying API data
  2. Implementing form submission and data registration
  3. Implementing file uploads and search functionality

By using these examples as references, you can build interactive web applications powered by the Fetch API. In the next section, we’ll summarize the entire article and introduce learning resources for your next steps.

8. Summary

In this article, we explained JavaScript’s Fetch API systematically—from the basics to practical use. The Fetch API is a powerful tool that enables asynchronous communication concisely and efficiently, making it essential for modern web application development.

Review of what you learned

  1. Overview and features of the Fetch API
  • The Fetch API is Promise-based, allowing concise and flexible code.
  • Compared to traditional XMLHttpRequest, the syntax is simpler and easier to maintain.
  1. Basic usage and error handling
  • Basic syntax for fetching data with GET requests.
  • By adding error handling and timeout processing, you can implement more robust code.
  1. Sending data with POST requests
  • Contoh mengirim data JSON dan data formulir.
  • Mempelajari cara menambahkan informasi otentikasi dan header khusus.
  1. Menggunakan pengaturan opsi secara efektif
  • Memperkenalkan metode kustomisasi fleksibel seperti kontrol cache, pengaturan CORS, dan manajemen kredensial.
  1. Contoh praktis
  • Mempelajari penggunaan nyata melalui contoh seperti tampilan daftar, pengiriman formulir, unggahan file, dan fungsi pencarian.

Keunggulan dan hal yang perlu diperhatikan untuk Fetch API

Keunggulan

  • Kode singkat dan sangat mudah dibaca.
  • Bekerja dengan baik bersama Promise dan Async/Await, memudahkan penggabungan dengan sintaks JavaScript modern.
  • Mendukung banyak format data seperti JSON, data biner, dan stream.

Hal yang perlu diperhatikan

  • Tidak ada fitur timeout secara default, sehingga Anda mungkin perlu mengimplementasikannya sendiri.
  • Tidak didukung di browser lama (misalnya Internet Explorer), jadi pertimbangkan polyfill atau alternatif bila diperlukan.

Sumber belajar untuk langkah selanjutnya

Untuk memperdalam pemahaman Anda tentang Fetch API, gunakan dokumentasi resmi dan sumber berikut ini.

Kesimpulan

Fetch API adalah alat yang kuat yang memungkinkan Anda mengimplementasikan komunikasi server secara sederhana menggunakan teknik JavaScript modern. Dengan menerapkan apa yang Anda pelajari dalam artikel ini, Anda dapat membangun aplikasi web yang lebih interaktif dan kaya fitur.

Seiring perkembangan web terus berlanjut, integrasi API dan pemrosesan asynchronous akan menjadi semakin penting. Kuasai Fetch API dan asah keterampilan praktis Anda!

Langkah selanjutnya

  • Cobalah membuat proyek yang menggunakan API nyata.
  • Gunakan opsi khusus untuk mengimplementasikan penanganan permintaan yang lebih maju.
  • Tantang diri Anda untuk membangun aplikasi full‑stack yang terintegrasi dengan backend sisi server.

Artikel ini selesai. Kami harap mempelajari Fetch API membantu Anda meningkatkan keterampilan lebih jauh lagi!

広告