비동기 통신
Axios를 사용하여 서버와 HTTP 통신을 수행하고 데이터를 주고받을 수 있다.
1️⃣ 비동기 통신 개요
동기 vs 비동기
| 구분 | 동기 통신 | 비동기 통신 |
|---|---|---|
| 처리 방식 | 요청 → 응답 대기 → 다음 작업 | 요청 → 다른 작업 진행 → 응답 처리 |
| 적합한 경우 | 은행 서비스 (정확성 중요) | SNS 타임라인 (속도 중요) |
| 사용자 경험 | 응답 대기 중 화면 멈춤 | 응답 대기 중에도 다른 작업 가능 |
- 동기 통신: 브라우저가 서버에 요청을 보낸 후 응답이 올 때까지 다음 동작을 실행하지 않음
- 비동기 통신: 브라우저가 서버에 요청을 보낸 후 응답을 기다리는 동안 다른 작업을 수행할 수 있음
- 웹 브라우저는 HTTP 요청을 통해 서버와 통신한다.
- 서버는 JSON, HTML, 이미지 등의 형식으로 응답을 반환한다.
- 웹 페이지에서는 사용자 경험을 고려하여 비동기 통신을 주로 사용한다.
2️⃣ RESTful API
HTTP 메서드
| 메서드 | 역할 | CRUD |
|---|---|---|
GET |
리소스 조회 | Read |
POST |
리소스 생성 | Create |
PUT |
리소스 전체 수정 | Update |
PATCH |
리소스 일부 수정 | Update |
DELETE |
리소스 삭제 | Delete |
RESTful API 예시
GET /users → 사용자 목록 조회
GET /users/1 → ID가 1인 사용자 조회
POST /users → 새 사용자 생성
PUT /users/1 → 사용자 정보 전체 수정
PATCH /users/1 → 사용자 정보 일부 수정
DELETE /users/1 → ID가 1인 사용자 삭제
HTTP 상태 코드
| 코드 | 의미 |
|---|---|
200 OK |
요청 성공 |
201 Created |
리소스 생성 성공 |
400 Bad Request |
잘못된 요청 |
401 Unauthorized |
인증 실패 |
404 Not Found |
리소스 없음 |
500 Internal Server Error |
서버 오류 |
JSON 데이터 구조
{
"id": 1,
"title": "할 일 작성하기",
"completed": false
}
3️⃣ Axios를 이용한 API 호출
설치
npm install axios
Axios의 특징
- Promise 기반으로 동작
- 응답이 JSON으로 자동 변환
- API 요청 취소 가능
- 상태 코드 기반 오류 구분 용이
- Timeout 기능 지원
- 다양한 브라우저 지원
GET 요청 (데이터 조회)
import axios from 'axios';
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(res => console.log(res.data))
.catch(err => console.error(err));
POST 요청 (데이터 생성)
axios.post('https://jsonplaceholder.typicode.com/todos', {
title: '새로운 할 일',
completed: false
})
.then(res => console.log(res.data))
.catch(err => console.error(err));
PUT 요청 (전체 수정)
axios.put('https://jsonplaceholder.typicode.com/todos/1', {
id: 1,
title: '할 일 수정됨',
completed: true
})
.then(res => console.log(res.data))
.catch(err => console.error(err));
PATCH 요청 (일부 수정)
axios.patch('https://jsonplaceholder.typicode.com/todos/1', {
completed: true
})
.then(res => console.log(res.data))
.catch(err => console.error(err));
DELETE 요청 (데이터 삭제)
axios.delete('https://jsonplaceholder.typicode.com/todos/1')
.then(res => console.log('삭제 완료'))
.catch(err => console.error(err));
Timeout 설정
axios.get('https://jsonplaceholder.typicode.com/todos', {
timeout: 3000 // 3초 안에 응답 없으면 에러
})
.then(response => console.log('성공:', response.data))
.catch(error => {
if (error.code === 'ECONNABORTED') {
console.error('타임아웃 발생');
} else {
console.error('기타 오류:', error.message);
}
});
4️⃣ async/await를 이용한 비동기 처리
Promise 방식
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(res => console.log('응답:', res.data))
.catch(err => console.error('에러:', err));
async/await 방식
- 비동기 코드를 동기 코드처럼 작성할 수 있다.
- 코드 가독성이 향상된다.
async function getTodo() {
try {
const res = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
console.log('응답:', res.data);
} catch (err) {
console.error('에러:', err);
}
}
getTodo();
try/catch를 통한 에러 처리
async function getTodo() {
try {
const res = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
console.log('응답 데이터:', res.data);
} catch (err) {
if (err.response) {
// 서버가 응답했지만 에러 상태 코드
console.error('서버 오류:', err.response.status);
console.error('에러 데이터:', err.response.data);
} else if (err.request) {
// 요청은 보냈지만 응답 없음
console.error('응답 없음:', err.request);
} else {
// 요청 자체에 문제
console.error('요청 오류:', err.message);
}
}
}
5️⃣ React에서 Axios 사용하기
기본 예제: 데이터 불러오기
import { useState, useEffect } from 'react';
import axios from 'axios';
function TodoList() {
const [todos, setTodos] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
fetchTodos();
}, []);
const fetchTodos = async () => {
setLoading(true);
setError(null);
try {
const res = await axios.get('https://jsonplaceholder.typicode.com/todos?_limit=5');
setTodos(res.data);
} catch (err) {
setError('데이터를 불러오는데 실패했습니다.');
console.error(err);
} finally {
setLoading(false);
}
};
if (loading) return <p>로딩 중...</p>;
if (error) return <p style={{ color: 'red' }}>{error}</p>;
return (
<div>
<h1>Todo 리스트</h1>
<ul>
{todos.map(todo => (
<li key={todo.id}>
{todo.title}
</li>
))}
</ul>
</div>
);
}
export default TodoList;
6️⃣ Axios vs Fetch API
| 비교 | Axios | Fetch API |
|---|---|---|
| 설치 | 필요 (npm install axios) |
불필요 (내장) |
| JSON 파싱 | 자동 (res.data) |
수동 (.json()) |
| 에러 처리 | HTTP 에러 자동 감지 | 수동 확인 (res.ok) |
| Timeout | 지원 | 미지원 |
| 코드 길이 | 짧고 간결 | 다소 김 |
| 브라우저 호환성 | 폴리필 포함 | 최신 브라우저만 지원 |
'GDGoC > FrontEnd' 카테고리의 다른 글
| [Frontend] #05. React - React Router와 전역 상태 관리 (0) | 2026.05.06 |
|---|---|
| [Frontend] #04. React - State와 Hooks (0) | 2026.05.06 |
| [Frontend] #03. React 기초 (0) | 2026.05.06 |
| [Frontend] #02. JavaScript (0) | 2026.05.06 |
| [Frontend] #01. HTML / CSS (0) | 2026.05.06 |