Axios는 자바스크립트에서 가장 인기 있는 HTTP 클라이언트 라이브러리 중 하나입니다. 브라우저와 Node.js 환경에서 모두 사용할 수 있으며, HTTP 요청을 보내고 응답을 받는 기능을 제공합니다. 이번 포스트에서는 Axios의 주요 기능과 사용법에 대해 소개하고, 실제 예시를 통해 Axios를 활용하는 방법을 알아보겠습니다.
Axios를 사용하기 위해서는 먼저 해당 라이브러리를 프로젝트에 설치해야 합니다. Node.js 환경에서는 npm을 사용하여 설치할 수 있습니다.
npm install axios
Axios를 사용하여 HTTP 요청을 보내는 기본적인 방법은 다음과 같습니다:
const axios = require('axios');
// GET 요청 보내기
axios.get('https://api.example.com/posts')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
// POST 요청 보내기
axios.post('https://api.example.com/posts', { title: 'New Post', body: 'Hello, Axios!' })
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
Axios는 요청과 응답을 가로채는 인터셉터(interceptor) 기능을 제공합니다. 이를 사용하여 요청 전에 헤더를 설정하거나 응답을 가공하는 등의 작업을 수행할 수 있습니다.
axios.interceptors.request.use(config => {
// 요청 전에 수행할 작업들
config.headers.Authorization = 'Bearer ' + localStorage.getItem('token');
return config;
});
axios.interceptors.response.use(response => {
// 응답을 가공하는 작업들
response.data = response.data.results;
return response;
});
Axios는 HTTP 요청 중 발생하는 에러를 쉽게 처리할 수 있는 기능을 제공합니다. .catch() 메서드를 사용하여 에러를 처리하거나, 인터셉터를 활용하여 공통적인 에러 처리 로직을 구현할 수 있습니다.
axios.get('https://api.example.com/posts')
.then(response => {
console.log(response.data);
})
.catch(error => {
if (error.response) {
// 응답 에러 처리
throw new Error(error.response.status);
} else if (error.request) {
// 요청 에러 처리
throw new Error(error.request);
} else {
// 기타 에러 처리
throw new Error(error.message);
}
});
이번 포스트에서는 Axios라는 자바스크립트 HTTP 클라이언트 라이브러리에 대해 알아보았습니다. Axios는 간편한 사용법과 다양한 기능을 제공하여 HTTP 요청을 보내고 응답을 처리하는 데 유용하게 활용될 수 있습니다. Axios의 공식 문서를 참고하여 더 많은 기능을 알아보시기 바랍니다.
https://axios-http.com/kr/docs/intro