Axios는 브라우저(또는 Node.js) 환경에서
서버와 HTTP 통신을 쉽게 해주는 Promise 기반 비동기 통신 라이브러리
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
npm install axios
설치 후 import
import axios from "axios";
axios.메소드명("요청URL", data, option);
| 구분 | 설명 |
|---|---|
| 메소드명 | get, post, put, delete, patch |
| 요청 URL | 통신할 API 주소 (ex: /api/user) |
| data(body) | 서버에 보낼 데이터 객체 (post, put 전용) |
| option | HTTP header, 인증 정보 등 설정 |
예시)
axios.post('/api/login', { id: 'yujin', pw: '1234' })
.then(res => console.log(res.data))
.catch(err => console.error(err));
axios.post('/api/test', data, {
headers: { 'Content-Type': 'application/json' }
});
const formData = new FormData();
formData.append("file", file);
formData.append("title", "사진 제목");
axios.post('/api/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
});
axios.get('/api/user', {
headers: { Authorization: `Bearer ${token}` }
});
axios.get('/api/search', {
params: { keyword: 'korean', page: 1 }
});
axios.get('/api/data')
.then(res => console.log(res.data))
.catch(err => console.error(err));
async function loadData() {
await axios.get('/api/data')
.then(res => console.log(res.data))
.catch(err => console.error(err));
}
async function loadData() {
try {
const res = await axios.get('/api/data');
console.log(res.data);
} catch (err) {
console.error(err);
}
}
axios.defaults.baseURL = "http://localhost:8080";
axios.defaults.withCredentials = true; // 쿠키 포함
공통 로직(예: 토큰 자동 추가, 로딩 처리 등)에 활용
axios.interceptors.request.use(
config => {
console.log("요청 시작:", config.url);
return config;
},
error => Promise.reject(error)
);
axios.interceptors.response.use(
res => res,
error => {
console.error("응답 오류:", error);
return Promise.reject(error);
}
);
서로 도메인(Origin) 이 다를 경우, 브라우저가 보안상 요청을 차단
| 클라이언트 | 서버 | 결과 |
|---|---|---|
| React (localhost:5173) | Spring (localhost:8080) | ❌ CORS 오류 |
| JS (localhost:8080) | Spring (localhost:8080) | ✅ 정상 |
@CrossOrigin(origins = "http://localhost:5173")
@RestController
public class ExampleController {
@GetMapping("/example")
public String test() { return "OK"; }
}
또는 전역 설정 (WebConfig.java)
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:5173")
.allowedMethods("*")
.allowCredentials(true);
}
}
const res = await axios.get('/api/user');
console.log(res.data); // 응답 본문
console.log(res.status); // HTTP 상태 코드 (200, 404 등)
const [user, posts] = await Promise.all([
axios.get('/api/user'),
axios.get('/api/posts')
]);
.catch(err => {
console.log(err.response.status); // 상태 코드
console.log(err.response.data); // 에러 메시지
});
| 구분 | 설명 |
|---|---|
| 장점 | JSON 자동 변환, Promise 기반, 설정 간편 |
| 주요 메서드 | get, post, put, delete, patch |
| 비동기 처리 | .then, .catch, async/await |
| CORS 해결 | @CrossOrigin, WebConfig 설정 |
| 옵션 | headers, params, withCredentials |
| 전역 설정 | axios.defaults, interceptors |