Axios

Axios는 브라우저와 Node.js를 위한 Promise 기반 HTTP 클라이언트 라이브러리입니다. 주로 웹 애플리케이션에서 서버와의 HTTP 통신을 간편하게 처리하기 위해 사용되며, XMLHttpRequest에 대한 대안으로 널리 채택되었습니다.

개요

Axios는 2014년 Matt Zabriskie에 의해 처음 공개되었으며, 현재는 GitHub에서 오픈 소스로 유지보수되고 있습니다. 브라우저 환경에서는 XMLHttpRequest를, Node.js 환경에서는 http 모듈을 활용하여 HTTP 요청을 처리합니다. 간결한 API와 강력한 기능으로 인해 React, Vue, Angular 등 다양한 프론트엔드 프레임워크와 함께 자주 사용됩니다.

주요 기능

1. Promise API 지원: 비동기 요청을 처리하기 위해 Promise를 기반으로 설계되어 async/await 문법과 호환됩니다.

2. 요청 및 응답 인터셉트: 요청을 보내기 전이나 응답을 받은 후에 가로채어 변형하거나 로깅할 수 있습니다.

3. 자동 JSON 변환: 서버에서 받은 JSON 데이터를 자동으로 JavaScript 객체로 변환합니다.

4. 취소 요청 지원: 요청을 중간에 취소할 수 있는 기능을 제공합니다.

5. CSRF 보호: Cross-Site Request Forgery 공격을 방지하기 위한 내장 보호 기능을 포함합니다.

6. 동시 요청 처리: axios.all()과 axios.spread()를 통해 여러 요청을 동시에 처리할 수 있습니다.

설치 방법

npm 사용 시

bash

npm install axios

yarn 사용 시

bash

yarn add axios

브라우저에서 직접 로드 시

html

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

기본 사용법

javascript

// GET 요청 예시

axios.get('/user?ID=12345')

.then(function (response) {

console.log(response.data);

})

.catch(function (error) {

console.error(error);

});

// POST 요청 예시

axios.post('/user', {

firstName: 'Fred',

lastName: 'Flintstone'

})

.then(function (response) {

console.log(response);

});

// async/await 사용 예시

async function getUser() {

try {

const response = await axios.get('/user?ID=12345');

console.log(response.data);

} catch (error) {

console.error(error);

}

}

요청 구성 옵션

Axios는 요청 시 다양한 설정 옵션을 제공합니다.

javascript

axios({

method: 'post',

url: '/user/12345',

data: {

firstName: 'Fred',

lastName: 'Flintstone'

},

headers: {'X-Custom-Header': 'foobar'},

timeout: 1000,

responseType: 'json'

});

전역 설정

Axios 인스턴스를 생성하거나 전역 기본값을 설정할 수 있습니다.

javascript

// 전역 기본 URL 설정

axios.defaults.baseURL = 'https://api.example.com';

// 전역 헤더 설정

axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

// 사용자 정의 인스턴스 생성

const instance = axios.create({

baseURL: 'https://api.example.com',

timeout: 1000,

headers: {'X-Custom-Header': 'foobar'}

});

인터셉터

요청 또는 응답을 then이나 catch로 처리하기 전에 가로챌 수 있습니다.

javascript

// 요청 인터셉터

axios.interceptors.request.use(

config => {

// 요청 전 작업 (예: 토큰 추가)

config.headers.Authorization = Bearer ${token};

return config;

},

error => {

return Promise.reject(error);

}

);

// 응답 인터셉터

axios.interceptors.response.use(

response => {

// 응답 데이터 가공

return response;

},

error => {

// 에러 처리

return Promise.reject(error);

}

);

에러 처리

Axios는 HTTP 상태 코드가 2xx 범위를 벗어나면 에러로 처리합니다.

javascript

axios.get('/user/12345')

.catch(error => {

if (error.response) {

// 서버가 2xx 외의 상태 코드로 응답

console.log(error.response.data);

console.log(error.response.status);

} else if (error.request) {

// 요청이 전송되었지만 응답을 받지 못함

console.log(error.request);

} else {

// 요청 설정 중 에러 발생

console.log('Error', error.message);

}

});

취소 요청

CancelToken을 사용하여 요청을 취소할 수 있습니다. (참고: v0.22.0부터는 CancelToken 대신 AbortController를 권장)

javascript

const CancelToken = axios.CancelToken;

const source = CancelToken.source();

axios.get('/user/12345', {

cancelToken: source.token

}).catch(thrown => {

if (axios.isCancel(thrown)) {

console.log('Request canceled', thrown.message);

}

});

// 요청 취소

source.cancel('Operation canceled by the user.');

브라우저 지원

Axios는 다음과 같은 브라우저를 지원합니다:

  • Chrome 최신 버전
  • Firefox 최신 버전
  • Safari 최신 버전
  • Edge 최신 버전
  • Internet Explorer 11 (Promise 폴리필 필요)

관련 프로젝트

  • axios-mock-adapter: Axios 요청을 모의(mocking)하기 위한 어댑터
  • axios-retry: 요청 실패 시 자동 재시도 기능
  • vue-axios: Vue.js와의 통합을 위한 래퍼

참고 자료

라이선스

Axios는 MIT 라이선스 하에 배포됩니다.

[[Category:JavaScript 라이브러리]]

[[Category:HTTP 클라이언트]]

[[Category:오픈 소스 소프트웨어]]