
웹 페이지에서 데이터를 요청하기 위해서는 서버와 통신을 해야 하는데요, Axios는 개발자가 손쉽게 HTTP 요청을 할 수 있도록 하는 JavaScript 라이브러리입니다. Promise API를 기반으로 동작하며 웹 브라우저 혹은 Node.js 환경에서 사용됩니다.
npm install axios
yarn add axios
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
axios.post('https://api.example.com/data', {name: 'geniee' })
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
// data를 객체 형식으로 만들었다면, 다음과 같은 형식으로 post 요청을 할 수 있습니다.
const data = {
name: 'geniee'
}
axios.post('https://api.example.com/data', data)
axios.put('https://api.example.com/data/1', { name: 'geniee1220' })
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
axios.delete('https://api.example.com/data/1')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
인스턴스를 사용하지 않는 일반적인 패턴에서의 요청에 헤더와 Content-Type을 어떻게 설정하는지 , 응답에서 어떤 값들을 확인하는지 설명합니다.
axios.get('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer token',
'Content-Type': 'application/json'
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.status); // HTTP 상태 코드를 확인할 수 있습니다.
console.log(response.headers); // 응답값의 헤더를 확인할 수 있습니다.
console.log(response.data); // 응답값 데이터를 확인할 수 있습니다.
})
.catch(error => {
console.error(error);
});
❗️ Axios는 HTTP 코드가 2xx이 아니라면(404, 500, 503 등등…) 에러로 처리합니다.
요청이나 응답을 할 때마다 추가해주어야 하는 기본 설정을 Instance로 묶어놓고 사용할 수 있습니다.
▼ Instance 사용하지 않았을 때의 코드입니다. 각 요청마다 필요한 header를 반복해서 적어주고 있는 것을 확인할 수 있습니다.
axios.get('https://api.example.com/data', {
headers: {
Authorization: 'Bearer token',
'Content-Type': 'application/json',
},
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
axios.get('https://api.example.com/post', {
headers: {
Authorization: 'Bearer token',
'Content-Type': 'application/json',
},
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
▼ Instance 사용했을 때의 코드입니다.
모든 요청에 사용하기 때문에 먼저 별도의 파일에서 인스턴스를 분리해서 정의합니다.
import axios, { AxiosInstance } from 'axios';
const baseURL = 'http://localhost:3000';
export const instance: AxiosInstance = axios.create({
baseURL: baseURL,
headers: { 'Content-Type': 'application/json' },
withCredentials: true,
});
export default instance;
사용할 때는, axios의 위치에 내가 정의한 인스턴스의 이름을 적어줍니다.
Instance를 사용했을 때는 각 요청마다 반복적으로 사용됐던 header 구문이 사라진 것을 확인할 수 있습니다.
import { instance } from '../api'
instance.get('https://api.example.com/data')
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
instance.get('https://api.example.com/post')
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
then 또는 catch로 처리되기 전에 요청과 응답을 가로채서 헤더 설정, 토큰 설정, 에러 스테이터스를 통한 처리 등 중간에 필요한 작업들을 추가해 줄 수 있습니다.
axios에서 제공하는 기본 인터셉터는 다음과 같은 방식으로 쓸 수 있습니다.
// 요청 인터셉터 추가하기
axios.interceptors.request.use(function (config) {
// 요청이 전달되기 전에 작업 수행
return config;
}, function (error) {
// 요청 오류가 있는 작업 수행
return Promise.reject(error);
});
// 응답 인터셉터 추가하기
axios.interceptors.response.use(function (response) {
// 2xx 범위에 있는 상태 코드는 이 함수를 트리거합니다.
// 응답 데이터가 있는 작업 수행
return response;
}, function (error) {
// 2xx 외의 범위에 있는 상태 코드는 이 함수를 트리거합니다.
// 응답 오류가 있는 작업 수행
return Promise.reject(error);
});
axios.post('https://api.example.com/upload', formData, {
// axios는 onDownloadProgress도 지원합니다.
onUploadProgress: progressEvent => {
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
console.log(`Upload progress: ${percentCompleted}%`);
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
❗️타입스크립트를 사용하는 경우 'progressEvent.total'은(는) 'undefined'일 수 있습니다.’라는 ****에러를 마주할 수 있는데, ??(Nullish coalescing 널 병합 연산자)로 undefined일 경우 기본값(1)을 설정해서 에러를 해결할 수 있습니다.
axios.post('https://api.example.com/upload', formData, {
onUploadProgress: progressEvent => {
const percentCompleted = Math.round(
((progressEvent?.loaded ?? 0) * 100) / (progressEvent?.total ?? 1)
);
console.log(`Upload progress: ${percentCompleted}%`);
}
})
Reference
⓵ https://yamoo9.github.io/axios/guide/api.html#구성-옵션
⓶ https://inpa.tistory.com/entry/AXIOS-📚-설치-사용