> For the complete documentation index, see [llms.txt](https://javascriptuse.gitbook.io/javascript/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://javascriptuse.gitbook.io/javascript/axios-vs-fetch-2020-nen-su-dung-thang-nao-voi-nhung-tinh-nang-moi-trong-javascript.md).

# Axios vs Fetch - 2020 nên sử dụng thằng nào với những tính năng mới trong javascript

#### Axios vs Fetch - 2020 nên sử dụng thằng nào với những tính năng mới trong javascript

**Nội dung bài viết**

* [1 - GET HTTP calls](https://anonystick.com/blog-developer/axios-vs-fetch-2020-nen-su-dung-thang-nao-voi-nhung-tinh-nang-moi-trong-javascript-2020010754182944?fbclid=IwAR0JBJLZwTB-rm0pKnj4h9Z6jCb3QQGKFJhPZjrh-5gb4eLABNy09saE4Es#t-0)
* [2 - POST HTTP calls](https://anonystick.com/blog-developer/axios-vs-fetch-2020-nen-su-dung-thang-nao-voi-nhung-tinh-nang-moi-trong-javascript-2020010754182944?fbclid=IwAR0JBJLZwTB-rm0pKnj4h9Z6jCb3QQGKFJhPZjrh-5gb4eLABNy09saE4Es#t-1)
* [3 - Error handling](https://anonystick.com/blog-developer/axios-vs-fetch-2020-nen-su-dung-thang-nao-voi-nhung-tinh-nang-moi-trong-javascript-2020010754182944?fbclid=IwAR0JBJLZwTB-rm0pKnj4h9Z6jCb3QQGKFJhPZjrh-5gb4eLABNy09saE4Es#t-2)
* [4 - Simultaneous requests](https://anonystick.com/blog-developer/axios-vs-fetch-2020-nen-su-dung-thang-nao-voi-nhung-tinh-nang-moi-trong-javascript-2020010754182944?fbclid=IwAR0JBJLZwTB-rm0pKnj4h9Z6jCb3QQGKFJhPZjrh-5gb4eLABNy09saE4Es#t-3)
* [5 - Upload](https://anonystick.com/blog-developer/axios-vs-fetch-2020-nen-su-dung-thang-nao-voi-nhung-tinh-nang-moi-trong-javascript-2020010754182944?fbclid=IwAR0JBJLZwTB-rm0pKnj4h9Z6jCb3QQGKFJhPZjrh-5gb4eLABNy09saE4Es#t-4)
* [Kết Luận](https://anonystick.com/blog-developer/axios-vs-fetch-2020-nen-su-dung-thang-nao-voi-nhung-tinh-nang-moi-trong-javascript-2020010754182944?fbclid=IwAR0JBJLZwTB-rm0pKnj4h9Z6jCb3QQGKFJhPZjrh-5gb4eLABNy09saE4Es#t-5)

**Axios vs** [**Fetch**](https://anonystick.com/blog-developer/fetch-javascript-2019121692350668.jsx) - Nếu như bạn đã từng làm việt với HTTP calls trong javascript hay nodejs thì bạn cũng đã từng sử dụng 1 trong 2 thằng này. [**Axios**](https://anonystick.com/blog-developer/5-cach-de-thuc-hien-cac-yeu-cau-http-http-request-trong-nodejs-DoAYfVbr.jsx) là một module mạnh mẽ và phổ biến trong javascript, và tương tự [**Fetch**](https://anonystick.com/blog-developer/fetch-javascript-2019121692350668.jsx) được phát hành 2015 cho đến nay

Và bài này không phải để tìm hiểu sâu về [**Axios**](https://anonystick.com/blog-developer/5-cach-de-thuc-hien-cac-yeu-cau-http-http-request-trong-nodejs-DoAYfVbr.jsx) và [**Fetch**](https://anonystick.com/blog-developer/fetch-javascript-2019121692350668.jsx), vì những bài trước chúng tôi cũng đã nói chi tiết về các ưu và nhược điểm và cách sử dụng của từng thằng. Hôm nay trong bài này tôi lấy những ví dụ để so sánh xem bạn nên sử dụng thằng nào khi làm việc ở client.

Có một thông tin nho nhỏ về [**Axios**](https://anonystick.com/blog-developer/5-cach-de-thuc-hien-cac-yeu-cau-http-http-request-trong-nodejs-DoAYfVbr.jsx) đó là Nó đã được tải xuống từ **npm hơn 25 triệu lần vào tháng 10 năm 2019**. Một con số khủng khiếp, mà chúng ta cũng không ngạc nhiên, vì đa số hiện nay, chúng ta những developer javascript (devjs) đã sử dụng nodejs quá nhiều và tôi cũng không ngoại trừ là thường xuyên sử dụng Axios để [**setup cron-job**](https://anonystick.com/blog-developer/how-to-set-up-nodejs-cron-jobs-2019101818875436.jsx). Nhưng bạn có biết Axios đã dừng dự án này hai năm rồi không? Và theo một [**topic của redit**](https://www.reddit.com/r/javascript/comments/cp5qhm/askjs_the_sad_state_of_axios/) thì có thể nó thực sự đang chết. Hơn nữa **những lỗ hổng** đã được phát hiện khi sử dụng Axios bởi [snyk.io](https://snyk.io/blog/a-denial-of-service-vulnerability-discovered-in-the-axios-javascript-package-affecting-all-versions-of-the-popular-http-client/). Càng làm cho Axios dừng chân cho đến bây giờ. Các bạn cũng nên tìm hiểu chút ít để biết nhiều hơn. Nghề của chúng ta là vậy, đọc và tìm hiểu, thậm chí ghi lại và chúng ta sẽ nhớ nhiều hơn.

![axios vs fetch in javascript](https://res.cloudinary.com/dcpvrespg/image/upload/c_scale,w_500/v1578366204/blog/api-request/axios-fetch-javascript.jpg)

Bây giờ tôi sẽ làm những ví dụ nhỏ nhỏ về so sánh cách sử dụng giữa [**Axios**](https://anonystick.com/blog-developer/5-cach-de-thuc-hien-cac-yeu-cau-http-http-request-trong-nodejs-DoAYfVbr.jsx) và [**Fetch**](https://anonystick.com/blog-developer/fetch-javascript-2019121692350668.jsx) xem có cái gì đặc biệt hơn không? Và trong năm 2020 bạn nên chọn thằng nào để hoạt động trên browser.

### 1 - GET HTTP calls <a href="#t-0" id="t-0"></a>

**Using** [**Fetch**](https://anonystick.com/blog-developer/fetch-javascript-2019121692350668.jsx)

```
fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))
// {
//   "userId": 1,
//   "id": 1,
//   "title": "delectus aut autem",
//   "completed": false
// }
```

**Using** [**Axios**](https://anonystick.com/blog-developer/5-cach-de-thuc-hien-cac-yeu-cau-http-http-request-trong-nodejs-DoAYfVbr.jsx)

```
axios.get("https://jsonplaceholder.typicode.com/todos/1")
  .then(response => console.log("response", response.data))
// {
//   "userId": 1,
//   "id": 1,
//   "title": "delectus aut autem",
//   "completed": false
// }
```

Nhìn qua chúng ta cũng biết được khi sử dụng [**Fetch**](https://anonystick.com/blog-developer/fetch-javascript-2019121692350668.jsx) thì phải mất 2 lần promises chúng ta mới nhận được kết quả. Còn khi sử dụng với [**Axios**](https://anonystick.com/blog-developer/5-cach-de-thuc-hien-cac-yeu-cau-http-http-request-trong-nodejs-DoAYfVbr.jsx) thì không hề có chuyện đó. Nó lấy trực tiếp khi promise return.

### 2 - POST HTTP calls <a href="#t-1" id="t-1"></a>

**Using** [**Fetch**](https://anonystick.com/blog-developer/fetch-javascript-2019121692350668.jsx)

```
fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  body: JSON.stringify({
    title: "Title of post",
    body: "Post Body"
  })
})
  .then(res => {
    if (!response.ok) throw Error(response.statusText);
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.log(error));
```

**Using** [**Axios**](https://anonystick.com/blog-developer/5-cach-de-thuc-hien-cac-yeu-cau-http-http-request-trong-nodejs-DoAYfVbr.jsx)

```
  axios
  .post("https://jsonplaceholder.typicode.com/posts", {
    title: "Title of post",
    body: "Body of post"
  })
  .then(response => console.log(response.data))
  .catch(error => console.log(error));
```

Tương tự như GET thì khi sử dụng [**Fetch**](https://anonystick.com/blog-developer/fetch-javascript-2019121692350668.jsx) thì chúng ta phải convert data qua **JSON.stringify()**, với [**Axios**](https://anonystick.com/blog-developer/5-cach-de-thuc-hien-cac-yeu-cau-http-http-request-trong-nodejs-DoAYfVbr.jsx) thì chúng ta có thể bỏ một cách thoải mái.

**Notes:**

> The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

### 3 - Error handling <a href="#t-2" id="t-2"></a>

```
Using Fetch
fetch("https://jsonplaceholder.typicode.com/todos/100000")
  .then(response => {
    if (!response.ok) throw Error(response.statusText);
    return response.json();
  })
  .then(data => console.log("data", data))
  .catch(error => {
    console.log("error", error);
  });
// error Error: Not Found
```

**Using** [**Axios**](https://anonystick.com/blog-developer/5-cach-de-thuc-hien-cac-yeu-cau-http-http-request-trong-nodejs-DoAYfVbr.jsx)

```
axios
  .get("https://jsonplaceholder.typicode.com/todos/100000")
  .then(response => {
    console.log("response", response);
  })
  .catch(error => {
    console.log("error", error);
  });
// error Error: Not Found
```

Axios network errors một cách trực tiếp còn nếu bạn làm việc với Fetch thì bạn phải check propertie response.ok.

### 4 - Simultaneous requests <a href="#t-3" id="t-3"></a>

[**Serial and parallel trong promise**](https://anonystick.com/blog-developer/promise-javascript-serial-and-parallel-2019120990707959.jsx) là một khái niệm quan trọng, bạn cần luôn luôn sử dụng vì nó quyết định tới performance code của bạn. Ở đây chỉ là một ví dụ nhỏ trong các ví dụ mà những bài trước đã trình bày.

**Using** [**Fetch**](https://anonystick.com/blog-developer/fetch-javascript-2019121692350668.jsx)

```
Promise.all([
  fetch('https://api.github.com/users/anonystick'),
  fetch('https://api.github.com/users/anonystick')
])
.then(async([res1, res2]) => {
  const a = await res1.json();
  const b = await res2.json();
  console.log(a.login + ' has ' + a.public_repos + ' public repos on GitHub');
  console.log(b.login + ' has ' + b.public_repos + ' public repos on GitHub');
})
.catch(error => {
  console.log(error);
});
```

**Using** [**Axios**](https://anonystick.com/blog-developer/5-cach-de-thuc-hien-cac-yeu-cau-http-http-request-trong-nodejs-DoAYfVbr.jsx)

```
axios.all([
  axios.get('https://api.github.com/users/anonystick'), 
  axios.get('https://api.github.com/users/anonystick')
])
.then(axios.spread((obj1, obj2) => {
  // Both requests are now complete
  console.log(obj1.data.login + ' has ' + obj1.data.public_repos + ' public repos on GitHub');
  console.log(obj2.data.login + ' has ' + obj2.data.public_repos + ' public repos on GitHub');
}));
```

### 5 - Upload <a href="#t-4" id="t-4"></a>

Upload thì toi nghĩ cái quan trọng là làm sao quản lý được monitor the progress khi upload thôi, để làm được điểu đó thì [**Fetch**](https://anonystick.com/blog-developer/fetch-javascript-2019121692350668.jsx) chưa support. Trong khi đó chúng ta có thể sử dụng [**Axios**](https://anonystick.com/blog-developer/5-cach-de-thuc-hien-cac-yeu-cau-http-http-request-trong-nodejs-DoAYfVbr.jsx) trong trường hợp này

```
const config = {
  onUploadProgress: event => console.log(event.loaded)
};
axios.put("/api", data, config);
```

### Kết Luận <a href="#t-5" id="t-5"></a>

Trên đây là những ví dụ về so sánh giữa [**Axios**](https://anonystick.com/blog-developer/5-cach-de-thuc-hien-cac-yeu-cau-http-http-request-trong-nodejs-DoAYfVbr.jsx) và [**Fetch**](https://anonystick.com/blog-developer/fetch-javascript-2019121692350668.jsx). Trong năm 2020 bạn nên sử dụng gì. Với bạn nào sử dụng Node thì việc sử dụng Axios thì không bàn cãi, nhưng trên browser thì việc sử dụng khi nào thì nên cân nhắc.

Thanks for readding!

Ref: [medium.com/](https://medium.com/frontend-digest/axios-vs-fetch-which-to-use-in-2019-6678c083c5c)

**Có thể bạn đã bị miss**

* [Firebase là gì? Tips and tricks firebase](https://anonystick.com/blog-developer/firebase-la-gi-tips-and-tricks-firebase-2020052675125066)
* [https là gì và có thực sự an toàn không?](https://anonystick.com/blog-developer/https-la-gi-va-co-thuc-su-an-toan-khong-2020072318940630)
* [Có bao nhiêu cách tìm một phần tử trong một mảng, Cảm ơn anh đã đến phỏng vấn và xin chào!](https://anonystick.com/blog-developer/co-bao-nhieu-cach-tim-mot-phan-tu-trong-mot-mang-cam-on-anh-da-den-phong-van-va-xin-chao-2020100124185019)
* [Cơ chế đăng nhập với token hơn cookie và session như thế nào? - Phần 2](https://anonystick.com/blog-developer/co-che-dang-nhap-voi-token-hon-cookie-va-session-nhu-the-nao-phan-2-2020091142676664)
* [Common Database Rules for Firebase](https://anonystick.com/blog-developer/common-database-rules-for-firebase-2019072544341457)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://javascriptuse.gitbook.io/javascript/axios-vs-fetch-2020-nen-su-dung-thang-nao-voi-nhung-tinh-nang-moi-trong-javascript.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
