> For the complete documentation index, see [llms.txt](https://organization-bht.gitbook.io/it/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://organization-bht.gitbook.io/it/undefined-1/react-with-typescript/react/4./2-axios.md). Agents can also search and read this documentation through its [MCP server](https://organization-bht.gitbook.io/it/~gitbook/mcp).

# 2) Axios

## 1. Axios

Axios는 **브라우저와 Node.js 환경에서 모두 사용 가능한 HTTP 클라이언트 라이브러리**로, 주로 **API 서버와 통신**하기 위해 사용됩니다.

* **API(Application Programming Interface) ?** 서버와 클라이언트 간 데이터를 주고 받는 통신 방법

현재 React 프로젝트에서 **가장 많이 쓰이는 비동기 요청 도구**이기도 합니다.

### 1) Axios의 특징

| 특징                  | 설명                                   |
| ------------------- | ------------------------------------ |
| **간편한 문법**          | `fetch()`보다 짧고 직관적인 문법 제공            |
| **자동 JSON 변환**      | 응답 데이터를 자동으로 JSON으로 변환               |
| **HTTP 오류 자동 처리**   | 404, 500 같은 오류 코드도 `.catch()`로 처리 가능 |
| **요청/응답 인터셉터 지원**   | 요청 전, 응답 후 처리 로직을 삽입 가능              |
| **동기화된 인스턴스 생성 가능** | 공통 설정을 적용한 axios 인스턴스를 만들 수 있음       |
| **취소 토큰 지원**        | 요청을 중간에 취소할 수 있음 (CancelToken)       |
| **브라우저 호환성 좋음**     | 오래된 브라우저에서도 안정적으로 작동                 |

### 1) 설치방법 및 사용예시

* `npm install axios`

```javascript
import axios from 'axios';

// GET 요청
axios.get('https://api.example.com/data')
  .then(res => console.log(res.data))
  .catch(err => console.error(err));

// POST 요청
axios.post('https://api.example.com/data', {
    username: 'mkm',
    password: '1234'
})
  .then(res => console.log(res.data))
  .catch(err => console.error(err));

```

## 2. fetch() 함수를 활용한 비동기 통신과 비교

* JS 내장 함수인 fetch를 활용하여 api요청을 보낼 수 있다.
* 단, timeout설정, 인터섭터등의 고급 기능은 내장되어 있지 않으며 예외처리시 코드가 복잡해지기 때문에 되도록 Axios로 통일해서 사용하는 것이 좋다.

### 1) 자동 json변환

```javascript
// fetch는 res.json()을 따로 호출해야 함
fetch(url).then(res => res.json())

// axios는 자동으로 res.data에 JSON이 담김
axios.get(url).then(res => console.log(res.data));
```

### 2) 에러처리

#### 1. fetch함수의 예외처리

```javascript
fetch('/api')
  .then(res => {
    if (!res.ok) { // 응답결과가 404,500이라면 "직접 예외발생"시켜줘야함.
      throw new Error(`HTTP 오류 발생! 상태 코드: ${res.status}`);
    }
    return res.json();
  })
  .then(data => {
    console.log('받은 데이터:', data);
  })
  .catch(err => {
    console.error('에러 발생:', err.message);
  });
```

#### 2. axios의 예외처리

```tsx
axios.get('/api')
  .then(res => {
    console.log('받은 데이터:', res.data);  // axios는 응답 데이터를 바로 res.data로 제공
  })
  .catch(err => {
    console.error('에러 발생!');
    console.error('상태 코드:', err.response?.status);      // 404, 500 등
    console.error('에러 메시지:', err.response?.data);       // 서버에서 보내준 메시지
  });
```

### 3) 공통설정 기능

* JWT토큰과 같이 매 요청시마다 전달해야 하는 데이터를 공통설정을 통해 추가 가능

```jsx
const api = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 3000,
  headers: { 'Authorization': 'Bearer token' }
});

api.get('/data');
```

### 4) 요청 및 응답 인터셉터

* 공통헤더 추가, 요청로그 확인, 요청데이터 변환 , 로딩상태 관리 등

```javascript
axios.interceptors.request.use(config => {
  console.log('요청 전 처리');
  return config;
});

axios.interceptors.response.use(response => {
  console.log('응답 후 처리');
  return response;
});
```

### 5) 요청 취소

<pre class="language-javascript"><code class="lang-javascript"><strong>const controller = new AbortController();
</strong>axios.get('/api', { signal: controller.signal });

// abort함수로 요청 취소 가능(컴포넌트 언마운트시 자동 취소되도록 설정 가능)
controller.abort();
</code></pre>
