Post

Axios란

Axios란

Axios: JavaScript에서 HTTP 요청을 더 쉽게 쓰는 방법

1. Axios란?

Axios는 브라우저와 Node.js에서 작동하는 Promise 기반의 HTTP 클라이언트다. REST API와 통신할 때 주로 사용되며, 코드가 간결하고 직관적이라 fetch보다 많이 쓰인다.

요약: fetch보다 편하고, 오류 처리와 응답 구조가 일관적이다.


2. Axios 설치

브라우저

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

Node.js (프론트 프레임워크 포함)

1
npm install axios

3. 사용 예제

GET 요청

1
2
3
4
5
6
7
axios.get("https://api.example.com/user/1")
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.error(error);
  });

POST 요청

1
2
3
4
5
6
7
8
9
10
axios.post("https://api.example.com/login", {
  username: "user",
  password: "pass"
})
.then((res) => {
  console.log("로그인 성공:", res.data);
})
.catch((err) => {
  console.error("에러:", err);
});

4. 주요 기능 요약

기능설명
axios.get(url)GET 요청
axios.post(url, data)POST 요청
axios.put(url, data)PUT 요청
axios.delete(url)DELETE 요청
axios.defaults.headers기본 헤더 설정
axios.interceptors요청/응답 가로채기

5. fetch와 차이점

비교 항목fetchaxios
응답 JSON 파싱수동 (res.json())자동 (res.data)
에러 처리HTTP 에러는 catch로 안 감catch로 감
코드 길이상대적으로 김상대적으로 짧음
브라우저 지원최신 브라우저만IE도 polyfill로 가능
인터셉터, 취소 토큰미지원지원함

fetch 예 (불편한 방식)

1
2
3
4
5
6
7
fetch("https://api.example.com/user/1")
  .then(res => {
    if (!res.ok) throw new Error("HTTP 에러");
    return res.json();
  })
  .then(data => console.log(data))
  .catch(err => console.error(err));

6. 실무 적용 예시

✅ Notion-Mind

  • 문제: GCP 서버에서 Notion API를 래핑해 프론트에서 비동기로 호출
  • 해결: axios로 GET/POST 요청 간단 처리. 응답 구조 일관성 확보.
  • 추가: 응답 지연, 오류 발생 시 사용자에게 Alert 처리하기 위해 interceptor 사용
1
2
3
4
5
6
7
axios.interceptors.response.use(
  (res) => res,
  (err) => {
    alert("서버 에러가 발생했습니다");
    return Promise.reject(err);
  }
);

7. 결론

  • axios는 HTTP 통신을 쉽게 만들기 위한 표준 도구
  • fetch보다 에러 처리, 응답 구조, 코드 가독성이 낫다
  • 실무에선 axios가 더 많이 쓰인다. 특히 인터셉터, 헤더 자동 처리, 응답 파싱에서 강점이 있다.

요즘 대부분의 프론트엔드 프로젝트(Vue, React, Next, Nuxt 등)에서는 axios가 기본 패키지처럼 쓰이고 있음.

This post is licensed under CC BY 4.0 by the author.