Hướng dẫn JavaScript Fetch API: GET, POST, Xử lý lỗi và Các ví dụ thực tế

1. Giới thiệu

JavaScript là một trong những ngôn ngữ lập trình được sử dụng rộng rãi nhất trong phát triển web. Trong số rất nhiều tính năng của nó, Fetch API đã thu hút sự chú ý như một khả năng quan trọng để thực hiện giao tiếp bất đồng bộ.

Trong bài viết này, chúng tôi sẽ giải thích chi tiết về Fetch API — từ những kiến thức cơ bản đến các cách sử dụng nâng cao. Khi hiểu rõ nó, bạn sẽ có thể thực hiện việc lấy dữ liệu và giao tiếp với máy chủ một cách mượt mà hơn trong các ứng dụng web.

Giao tiếp bất đồng bộ là gì?

Giao tiếp bất đồng bộ là một phương pháp trao đổi dữ liệu với máy chủ trong khi vẫn tiếp tục các xử lý khác mà không bị chặn cho đến khi giao tiếp hoàn tất. Điều này cải thiện độ phản hồi của giao diện người dùng và giúp xử lý dữ liệu dễ dàng hơn mà không gây bực bội.

Ví dụ, khi người dùng nhấn một nút trên trang web để lấy dữ liệu, các tác vụ khác có thể tiếp tục mà không phải chờ phản hồi từ máy chủ, từ đó nâng cao đáng kể trải nghiệm người dùng.

Fetch API là gì?

Fetch API là một giao diện hiện đại để thực hiện giao tiếp bất đồng bộ trong JavaScript. Nó được giới thiệu như một lựa chọn thay thế cho XMLHttpRequest (XHR) truyền thống, cung cấp cú pháp ngắn gọn và cấu hình linh hoạt.

Với API này, bạn có thể dễ dàng viết logic để lấy dữ liệu từ máy chủ hoặc gửi dữ liệu tới máy chủ.

Trong các phần tiếp theo, chúng tôi sẽ giới thiệu mọi thứ từng bước — từ cách sử dụng cơ bản của Fetch API đến các ví dụ thực tế, áp dụng trong dự án thực tế.

2. Fetch API là gì?

Fetch API là giao diện tiêu chuẩn mới nhất để thực hiện giao tiếp bất đồng bộ trong JavaScript. Trong phần này, chúng tôi sẽ giải thích vai trò cơ bản của nó và cách nó khác biệt so với các phương pháp truyền thống.

Tổng quan về Fetch API

Fetch API được thiết kế để lấy các tài nguyên qua mạng.
Điều này giúp các ứng dụng web dễ dàng giao tiếp với máy chủ.

Các tính năng chính

  • Dựa trên Promise : Không cần dựa vào các hàm callback, cho phép bạn viết mã dễ đọc hơn.
  • Cú pháp ngắn gọn : So với XMLHttpRequest, nó có thể giảm đáng kể lượng mã cần viết.
  • Linh hoạt cao : Bạn có thể tùy chỉnh yêu cầu và phản hồi một cách chi tiết.
  • Thiết kế hiện đại : Hoạt động tốt với các tính năng mới của JavaScript, giúp mã dễ bảo trì.

Dưới đây là một ví dụ cơ bản về cách sử dụng 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

Đoạn mã này lấy dữ liệu từ URL được chỉ định, chuyển đổi nó sang JSON và hiển thị trong console. Nếu có lỗi xảy ra, nó sẽ in ra thông báo lỗi.

Khác biệt so với XMLHttpRequest truyền thống

Fetch API là một cách tiếp cận mới thay thế XMLHttpRequest (XHR) được sử dụng rộng rãi. Bảng dưới đây so sánh hai phương pháp.

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

Như bạn thấy, Fetch API hấp dẫn nhờ thiết kế ngắn gọn và hiện đại. Đặc biệt, việc dựa trên Promise cho phép bạn viết logic bất đồng bộ một cách tự nhiên hơn.

Tóm tắt

Fetch API là một công cụ mạnh mẽ và dễ sử dụng cho giao tiếp bất đồng bộ trong JavaScript. Vì nó đơn giản hơn so với XHR truyền thống, nên đã trở thành một kỹ năng thiết yếu cho phát triển web hiện đại.

Trong phần tiếp theo, chúng tôi sẽ hướng dẫn các mẫu sử dụng cụ thể của Fetch API kèm theo các ví dụ mã nguồn.

3. Cách sử dụng cơ bản của Fetch API

Trong phần này, chúng tôi sẽ giải thích cách sử dụng cơ bản của Fetch API kèm theo các ví dụ mã thực tế. Chủ yếu chúng tôi sẽ đề cập đến các nội dung sau.

  • Cú pháp của phương thức fetch() và một ví dụ cơ bản
  • Cách thực hiện yêu cầu GET
  • Cách xử lý dữ liệu phản hồi

Cú pháp cơ bản của phương thức fetch()

Với Fetch API, bạn gửi yêu cầu tới máy chủ bằng phương thức fetch(). Dưới đây là cú pháp cơ bản.

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

Đối số

. url : URL mà yêu cầu được gửi tới.
options (tùy chọn): Các thiết lập tùy chọn bao gồm phương thức, header, body và các tùy chọn khác.

Giá trị trả về

  • Promise object : Trả về kết quả của quá trình bất đồng bộ.

Cách thực hiện yêu cầu GET

Cách sử dụng cơ bản nhất của Fetch API là yêu cầu GET, dùng để lấy dữ liệu từ máy chủ.

Ví dụ: Lấy dữ liệu 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
  });

Cách xử lý dữ liệu phản hồi

Với Fetch API, bạn có thể xử lý dữ liệu phản hồi ở nhiều định dạng khác nhau. Dưới đây là các ví dụ phổ biến.

  1. Lấy dữ liệu dạng văn bản
    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. Lấy dữ liệu nhị phân
    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. Lấy thông tin 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));
    

Tổng kết

Ở phần này, chúng ta đã giới thiệu cách thực hiện một yêu cầu GET cơ bản bằng Fetch API và cách xử lý phản hồi.

Fetch API là một công cụ linh hoạt, giúp bạn dễ dàng lấy nhiều loại dữ liệu như văn bản, JSON và dữ liệu nhị phân. Khi đã nắm vững các nguyên tắc cơ bản này, bạn sẽ dễ dàng áp dụng chúng trong các chương tiếp theo, bao gồm xử lý lỗi và các yêu cầu POST.

Trong phần tiếp theo, chúng ta sẽ giải thích chi tiết về xử lý lỗi với Fetch API.

4. Xử lý lỗi

Trong mục này, chúng ta sẽ trình bày cách xử lý lỗi khi sử dụng Fetch API. Khi giao tiếp với máy chủ, có thể xảy ra nhiều vấn đề như lỗi mạng và lỗi phản hồi. Xử lý chúng một cách thích hợp sẽ cải thiện trải nghiệm người dùng.

Những nguyên tắc cơ bản của xử lý lỗi

Với Fetch API, bạn có thể dùng phương thức catch() để xử lý các trường hợp như thất bại mạng hoặc phản hồi lỗi.

Ví dụ cơ bản về xử lý lỗi

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

Xử lý lỗi với try…catch

Sử dụng Async/Await cho phép bạn viết mã sạch hơn, dễ đọc hơn. Trong trường hợp này, bạn sẽ xử lý lỗi bằng câu lệnh try...catch.

Ví dụ: Xử lý lỗi với 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();

Triển khai timeout

Fetch API không có tính năng timeout tích hợp sẵn theo mặc định. Tuy nhiên, việc triển khai timeout sẽ giúp bạn xử lý các phản hồi chậm một cách hợp lý.

Ví dụ: Triển khai 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(`Lỗi HTTP! Trạng thái: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Đã xảy ra lỗi:', 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('Lỗi mạng:', 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('Lỗi:', 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(`Lỗi HTTP! Trạng thái: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log('Thành công:', data))
  .catch(error => console.error('Lỗi:', 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('Tải lên thành công:', data))
  .catch(error => console.error('Lỗi:', 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('Thành công:', data))
  .catch(error => console.error('Lỗi:', 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(`Lỗi HTTP! Trạng thái: ${response.status}`);
    }

    const result = await response.json();
    console.log('Thành công:', result);
  } catch (error) {
    console.error('Đã xảy ra lỗi:', error.message);
  }
}

postData('https://example.com/api/messages', { text: 'Xin chào!' });

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('Lỗi:', 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: 'Xin chào!' }),
  credentials: 'include',
  mode: 'cors',
  cache: 'no-cache',
  redirect: 'follow',
})
  .then(response => response.json())
  .then(data => console.log('Thành công:', data))
  .catch(error => console.error('Lỗi:', 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(`Lỗi HTTP! Trạng thái: ${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('Lỗi:', 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(`Lỗi HTTP! Trạng thái: ${response.status}`);
    }

    const result = await response.json();
    console.log('Đăng ký thành công:', result);
    alert('Người dùng đã được đăng ký!');
  } catch (error) {
    console.error('Lỗi:', error);
    alert('Đã xảy ra lỗi.');
  }
});

HTML example

<form id="user-form">
  <input type="text" id="name" placeholder="Tên" required />
  <input type="email" id="email" placeholder="Địa chỉ email" required />
  <button type="submit">Đăng ký</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(`Lỗi HTTP! Trạng thái: ${response.status}`);
    }

    const result = await response.json();
    console.log('Tải lên thành công:', result);
    alert('Tệp đã được tải lên!');
  } catch (error) {
    console.error('Lỗi:', error);
    alert('Tải lên thất bại.');
  }
});

HTML example

<input type="file" id="file-input" />
<button id="upload-button">Tải lên</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

. Các ví dụ về việc gửi dữ liệu JSON và dữ liệu biểu mẫu.
Học cách thêm thông tin xác thực và tiêu đề tùy chỉnh.

  1. Sử dụng cài đặt tùy chọn một cách hiệu quả
  • Giới thiệu các phương pháp tùy chỉnh linh hoạt như kiểm soát bộ nhớ đệm, cài đặt CORS và quản lý thông tin xác thực.
  1. Các ví dụ thực tế
  • Học cách sử dụng thực tế qua các ví dụ như hiển thị danh sách, gửi biểu mẫu, tải lên tệp và chức năng tìm kiếm.

Ưu điểm và lưu ý cho Fetch API

Ưu điểm

  • Mã ngắn gọn và dễ đọc.
  • Hoạt động tốt với Promises và Async/Await, giúp dễ dàng kết hợp với cú pháp JavaScript hiện đại.
  • Hỗ trợ nhiều định dạng dữ liệu như JSON, dữ liệu nhị phân và luồng.

Lưu ý

  • Không có tính năng timeout mặc định, vì vậy bạn có thể cần tự triển khai.
  • Không được hỗ trợ trên các trình duyệt cũ (ví dụ Internet Explorer), vì vậy hãy cân nhắc sử dụng polyfill hoặc các giải pháp thay thế nếu cần.

Tài nguyên học tập cho các bước tiếp theo

Để nâng cao hiểu biết về Fetch API, hãy sử dụng tài liệu chính thức và các nguồn dưới đây.

Kết luận

Fetch API là công cụ mạnh mẽ cho phép bạn thực hiện giao tiếp với máy chủ một cách đơn giản bằng các kỹ thuật JavaScript hiện đại. Bằng cách áp dụng những gì bạn đã học trong bài viết này, bạn có thể xây dựng các ứng dụng web tương tác hơn và giàu tính năng hơn.

Khi phát triển web không ngừng tiến bộ, việc tích hợp API và xử lý bất đồng bộ sẽ ngày càng quan trọng. Hãy thành thạo Fetch API và nâng cao kỹ năng thực tiễn của bạn!

Các bước tiếp theo

  • Thử tạo một dự án sử dụng API thực.
  • Sử dụng các tùy chọn tùy chỉnh để triển khai xử lý yêu cầu nâng cao hơn.
  • Thử thách bản thân xây dựng các ứng dụng full-stack tích hợp với backend phía máy chủ.

Đây là kết thúc của bài viết. Chúng tôi hy vọng việc học Fetch API sẽ giúp bạn nâng cao kỹ năng hơn nữa!

広告