0

Xử lý API trong JavaScript & React: Từ cơ bản đến chuyên sâu

Trong bài viết này sẽ giới thiệu cho các bạn học cách xử lý API trong JavaScript với fetch, axios và quản lý lỗi. Xử lý API liên quan đến việc gửi yêu cầu HTTP đến máy chủ để lấy hoặc gửi dữ liệu. Hãy cùng theo dõi nhé!

API là gì?

API (Giao diện lập trình ứng dụng) là tập hợp các định nghĩa và giao thức cho phép hai thành phần phần mềm giao tiếp với nhau. Một số công nghệ được sử dụng để viết API bao gồm:

  • JavaScript (Express framework)
  • Python (Django framework)
  • Go (Gin framework)
  • Java (Spring Boot framework)
  • C# (ASP.NET Core framework)

Xử lý API là gì?

Xử lý API là quá trình gửi yêu cầu HTTP đến máy chủ để lấy hoặc gửi dữ liệu. Trong JavaScript và React, API thường được xử lý bằng fetch, Axios, hoặc các thư viện như React Query hoặc TanStack Query.

Các phương thức HTTP

API hoạt động với nhiều phương thức HTTP khác nhau, mỗi phương thức có một mục đích cụ thể:

  • GET – Lấy dữ liệu từ máy chủ.
  • POST – Gửi dữ liệu mới lên máy chủ.
  • PUT – Cập nhật toàn bộ dữ liệu hiện có.
  • PATCH – Cập nhật một phần của dữ liệu hiện có.
  • DELETE – Xóa dữ liệu khỏi máy chủ.

Thực hiện API Request trong JavaScript

1. Phương pháp fetch

Phương thức API fetch gốc thường được sử dụng để tương tác với API. Nó chấp nhận 2 đối số - điểm cuối API và các đối tượng tùy chọn để truyền tiêu đề, nội dung, phương thức, v.v.

Phương thức lấy dữ liệu với yêu cầu GET:

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => scrib.show(data))
  .catch(error => scrib.show('Error:', error));

Phương pháp lấy dữ liệu với yêu cầu POST:

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST', // type of method GET, POST, PUT, POST, DELETE
  headers: {
    'Content-Type': 'application/json' // headers like referrer, bearer, content-type, custom headers, etc.
  },
  // body of the POST request which we are sending to the api
  body: JSON.stringify({
    title: 'Javascript is awesome',
    body: 'Did you know you could write html and javascript combined in scribbler',
    userId: 1
  })
})
  .then(response => response.json())
  .then(data => scrib.show(data))
  .catch(error => scrib.show('Error:', error));

Xử lý lỗi với phương thức fetch:

fetch('https://jsonplaceho.typicode.com/posts') // incorrect api endpoint
  .then(response => response.json())
  .then(data => scrib.show(data))
  .catch(error => scrib.show('Error:', error)); // will run this block of code and throws error

Xử lý api với khối try catch finally:

async function getData() {
  try {
    let response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    if (!response.ok) throw new Error('Network response was not ok'); // return boolean for valid/invalid responses
    let data = await response.json();
    scrib.show(data)
  } catch (error) {
    scrib.show('Fetch error:', error); // will handle the error if the fetch fails
  } finally {
    scrib.show(Fetch request is done); // will run no matter a response is valid or invalid or fetch fails
  }
}
getData()

2. Axios

Axios là một thư viện javascript giúp đơn giản hóa việc xử lý API và xử lý lỗi tốt hơn.

Axiox với yêu cầu GET:

import axios from "axios"

// all http methods could be chained with axios
axios.get('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => scrib.show(response.data))
  .catch(error => scrib.show('Error:', error));

Axios với yêu cầu POST:

import axios from "axios"

// json body is passed separately as second argument and rest of the options as third argument
axios.post('https://jsonplaceholder.typicode.com/posts', {
   title: 'Javascript is awesome',
    body: 'Did you know you could write html and javascript combined in scribbler',
    userId: 1
}, {
  headers: { 'Content-Type': 'application/json' }
})
  .then(response => scrib.show(response.data)) // automatically converts the response to json format
  .catch(error => scrib.show('Error:', error));

Xử lý lỗi với axios:

import axios from "axios"

axios.get('https://jsonpl.typicode.com/posts') // incorrect url
  .then(response => scrib.show(response.data))
  .catch(error => {
// has multiple error response for different scenarios
    if (error.response) {
      scrib.show('Server responded with:', error.response.status);
    } else if (error.request) {
      scrib.show('No response received');
    } else {
      scrib.show('Error setting up request:', error.message);
    }
  });

Xử lý api với khối try catch finally:

import axios from "axios";

const fetchData = async () => {
  try {
    const response = await axios.get("https://jsonplaceholder.typicode.com/posts");
    console.log("Data fetched successfully:", response.data);
    return response.data;
  } catch (error) {
    console.error("Error fetching data:", error.response?.data || error.message);
    return null;
  } finally {
    console.log("Fetch is done")
  }
};

fetchData();

React (sử dụng useEffect và useState)

import { useEffect, useState } from 'react';

function Posts() {
  // Creating states for data and error messages
  const [posts, setPosts] = useState([]);
  const [error, setError] = useState(null);

  // Performing data fetching in useEffect, will run only once on page load
  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        if (!response.ok) {
          throw new Error('Failed to fetch');
        }
        return response.json();
      })
      .then(data => setPosts(data))
      .catch(error => setError(error.message));
  }, []);

  if (error) return <p>Error: {error}</p>;

  return (
    <div>
      <h2>Posts</h2>
      <ul>
        {posts.map(post => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}

export default Posts;

Thư viện truy vấn Tanstack

import { useQuery } from '@tanstack/react-query';
import axios from 'axios';

// fetch the data and return it
const fetchPosts = async () => {
  const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
  return data;
};

function Posts() {
  // tanstack has builtin data, error, loading states
  const { data: posts, error, isLoading } = useQuery({ queryKey: ['posts'], queryFn: fetchPosts });

  if (isLoading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <ul>
      {posts.map(post => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
}

export default Posts;

Kết luận

Xử lý API trong JavaScript và React bao gồm:

  • Sử dụng fetch hoặc Axios để gọi API.
  • Xử lý các phương thức HTTP khác nhau (GET, POST, PUT, DELETE).
  • Triển khai quản lý lỗi hiệu quả.
  • Quản lý headers để xác thực (authentication).
  • Sử dụng useEffect để gọi API trong React.
  • Ứng dụng React Query để tối ưu quản lý trạng thái.

All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí