AXIOS:비동기통신

·2025년 11월 4일

JS

목록 보기
7/7

Axios란?

Axios는 브라우저(또는 Node.js) 환경에서
서버와 HTTP 통신을 쉽게 해주는 Promise 기반 비동기 통신 라이브러리

주요 특징

  • JSON 데이터를 자동 변환(JSON.parse / JSON.stringify 불필요)
  • Promise 기반이라 async/await 사용 가능
  • 에러 및 응답 처리가 간단 (.then, .catch)
  • 요청 및 응답 인터셉터(interceptor) 기능 지원
  • 헤더, 토큰, 파일 업로드 등 옵션 설정 용이
  • 브라우저뿐 아니라 Node.js 백엔드에서도 사용 가능

설치 방법

(1) 브라우저 (CDN 방식)

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

(2) React / Node.js (npm 설치)

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 전용)
optionHTTP header, 인증 정보 등 설정

예시)

axios.post('/api/login', { id: 'yujin', pw: '1234' })
  .then(res => console.log(res.data))
  .catch(err => console.error(err));

옵션 설정 (Headers, Params 등)

(1) 기본 헤더 설정

axios.post('/api/test', data, {
  headers: { 'Content-Type': 'application/json' }
});

(2) 파일 업로드 (multipart/form-data)

const formData = new FormData();
formData.append("file", file);
formData.append("title", "사진 제목");

axios.post('/api/upload', formData, {
  headers: { 'Content-Type': 'multipart/form-data' }
});

(3) 인증 토큰 추가

axios.get('/api/user', {
  headers: { Authorization: `Bearer ${token}` }
});

(4) 쿼리스트링 방식 (GET)

axios.get('/api/search', {
  params: { keyword: 'korean', page: 1 }
});

응답 처리 패턴

(1) 비동기 방식 (.then / .catch)

axios.get('/api/data')
  .then(res => console.log(res.data))
  .catch(err => console.error(err));

(2) async/await + then

async function loadData() {
  await axios.get('/api/data')
    .then(res => console.log(res.data))
    .catch(err => console.error(err));
}

(3) async/await + try~catch

async function loadData() {
  try {
    const res = await axios.get('/api/data');
    console.log(res.data);
  } catch (err) {
    console.error(err);
  }
}

응용 — 전역 설정

(1) 기본 서버 주소 설정

axios.defaults.baseURL = "http://localhost:8080";
axios.defaults.withCredentials = true; // 쿠키 포함

(2) 요청/응답 인터셉터

공통 로직(예: 토큰 자동 추가, 로딩 처리 등)에 활용

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);
  }
);

CORS (Cross-Origin Resource Sharing)

⚠️문제 상황

서로 도메인(Origin) 이 다를 경우, 브라우저가 보안상 요청을 차단

클라이언트서버결과
React (localhost:5173)Spring (localhost:8080)❌ CORS 오류
JS (localhost:8080)Spring (localhost:8080)✅ 정상

해결 방법 (Spring Boot)

@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 등)

동시 요청 (Promise.all)

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

0개의 댓글