Skip to main content

Axios trong Next.js

Trong ứng dụng bất kỳ chúng ta luôn cần request đến server để lấy dữ liệu, ngoài cách sử dụng browser APIs là fetch chúng ta còn có thể sử dụng Axios

Axios là gì?

Axios là thư viện HTML Client dựa trên Promise dành cho trình duyệt website và Node.js.

Axios có thể chạy trên cả trình duyệt và server không như fetch. Fetch để sử dụng trong Node.js thì có thể sử dụng fetch-node.

Axios khi ở phía server thì nó sử dụng native module http trong node.js, còn ở phía client (trình duyệt) thì nó sử dụng XMLHttpRequest.

Một số lý do để bạn sử dụng Axios:

  • Axios có thể sử dụng trên cả trình duyệt và server
  • Tạo một Axios instance mặc định và dùng chung cho tất cả request HTTP
  • Có thể dừng request bất cứ lúc nào muốn
  • Có thể sử dụng HTTP Interceptors để sửa đổi request và response dễ dàng

Axios sẽ giúp b ạn tạo request HTTP đễ dàng và dễ quản lý hơn nhiều.

Hướng dẫn cài đặt Axios trong Next.js

Bước 1: Tạo Next.js app bằng lệnh dưới

yarn create next-app nextjs-app

or

npx create-next-app nextjs-app

Bước 2: Cài đặt Axios

cd nextjs-app

yarn add axios

Giờ bạn có thể sử dụng Axios trong Next.js rồi

Tạo một  GET Request với Axios và Next.js

ví dụ tạo file ./pages/index.js, lấy dữ liệu từ 

https://fakestoreapi.com/products

sau đó hiển thị danh sách product 

import axios from 'axios';

const Home = ({ products, error }) => {
  if (error) {
    return <div>An error occured: {error.message}</div>;
  }
  return (
    <ul>
      {products.map(restaurant => (
        <li key={products.id}>{products.title}</li>
      ))}
    </ul>
  );
};

Home.getInitialProps = async ctx => {
  try {
    const res = await axios.get('https://fakestoreapi.com/products');
    const products = res.data;
    return { products };
  } catch (error) {
    return { error };
  }
};

export default Home;

Tạo một  POST Request với Axios và Next.js

Tương tự bạn có thể sử dụng post request như sau

axios.post('https://fakestoreapi.com/products', {
    title: 'test product',
    price: 13.5,
    description: 'lorem ipsum set',
    image: 'https://i.pravatar.cc',
    category: 'electronic'
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

Ngoài 2 request GET/ POST phổ biến, Axios còn hỗ trợ:

  • axios.request(config)
  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.options(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])

Để hiểu hơn bạn có thể vảo Axios, hay trang Axios-HTTP có cả tiếng việt