Axios
발행: (2026년 1월 15일 오후 06:06 GMT+9)
2 min read
원문: Dev.to
Source: Dev.to

Axios 메서드
| 메서드 | 목적 |
|---|---|
axios.get() | 데이터 가져오기 |
axios.post() | 데이터 생성/전송 |
axios.put() | 전체 리소스 업데이트 |
axios.patch() | 부분 업데이트 |
axios.delete() | 데이터 삭제 |
프로젝트에서 Axios 사용 방법
단계 1: Axios 설치
npm install axios
# or
yarn add axios
단계 2: 기본 Axios 사용법
import axios from 'axios';
// GET request
axios.get('http://localhost:3000/api/users')
.then(response => console.log(response.data))
.catch(error => console.log(error));
// POST request
axios.post('http://localhost:3000/api/users', {
name: 'John',
email: 'john@example.com'
})
.then(response => console.log(response.data))
.catch(error => console.log(error));
// PUT request (update)
axios.put('http://localhost:3000/api/users/1', {
name: 'Jane'
})
.then(response => console.log(response.data))
.catch(error => console.log(error));
// DELETE request
axios.delete('http://localhost:3000/api/users/1')
.then(response => console.log(response.data))
.catch(error => console.log(error));
단계 3: React 컴포넌트에서 (Hooks 사용)
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
// Fetch data on component mount
useEffect(() => {
fetchUsers();
}, []);
const fetchUsers = async () => {
setLoading(true);
try {
const response = await axios.get('http://localhost:3000/api/users');
setUsers(response.data.users);
setError(null);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
if (loading) return
Loading...
;
if (error) return
Error: {error}
;
return (
{users.map(user => (
### {user.name}
{user.email}
))}
);
}
export default UserList;
단계 4: 인증과 함께 사용 (토큰 전송)
axios.post('http://localhost:3000/api/auth/login', {
email,
password
}, {
withCredentials: true, // Send cookies
headers: {
'Content-Type': 'application/json'
}
})
.then(response => console.log(response.data))
.catch(error => console.log(error));
단계 5: 재사용 가능한 Axios 인스턴스 만들기
src/api/axiosInstance.js 파일 생성:
import axios from 'axios';
const axiosInstance = axios.create({
baseURL: 'http://localhost:3000/api',
withCredentials: true
});
// Add token to all requests
axiosInstance.interceptors.request.use(config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
export default axiosInstance;
컴포넌트에서 인스턴스 사용:
import axiosInstance from '../api/axiosInstance';
// Instead of full URL
axiosInstance.post('/auth/login', { email, password })
.then(response => console.log(response.data))
.catch(error => console.log(error));