Axios
- Axios는 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리입니다.
- 쉽게 말해서 백엔드랑 프론트엔드랑 통신을 쉽게하기 위해 Ajax와 더불어 사용합니다.
- 이미 자바스크립트에는 멋진 fetch api가 있지만, 프레임워크에서 ajax를 구현할땐 axios를 쓰는 편이라고 보면 됩니다.
axios 특징
- 운영 환경에 따라 브라우저의 XMLHttpRequest 객체 또는 Node.js의 http api 사용
- Promise(ES6) API 사용
- 요청과 응답 데이터의 변형
- HTTP 요청 취소
- HTTP 요청과 응답을 JSON 형태로 자동 변경

예제 - GET 요청 수행
const axios = require('axios');
// 지정된 ID를 가진 유저에 대한 요청
axios.get('/user?ID=12345')
.then(function (response) {
// 성공 핸들링
console.log(response);
})
.catch(function (error) {
// 에러 핸들링
console.log(error);
})
.then(function () {
// 항상 실행되는 영역
});
// 선택적으로 위의 요청은 다음과 같이 수행될 수 있습니다.
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// 항상 실행되는 영역
});
// async/await 사용을 원한다면, 함수 외부에 `async` 키워드를 추가하세요.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
예제 - POST 요청 생성
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Axious API
axios(config) : axious에 해당 config을 전송하면 요청이 가능합니다.
axios(url[, config]) : url로 요청 수행, config가 없으면 자동으로 GET
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
Axiou 인스턴스
axious.create([config]) : 인스턴스 생성
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#options(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
axios#getUri([config])
Config 기본값
config 기본값을 지정할 수 있다.
전역 Axios 기본값
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] =AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
커스텀 인스턴스 기본값
// 인스턴스를 생성할때 config 기본값 설정하기
const instance = axios.create({
baseURL: 'https://api.example.com'
});
// 인스턴스를 만든 후 기본값 변경하기
instance.defaults.headers.common['Authorization'] =AUTH_TOKEN;
Config 우선 순위
Config는 우선 순위에 따라 병합됩니다. lib/defaults.js 라이브러리에서의 기본값, 인스턴스의
defaults
속성, 요청의 config
인자를 순서대로 찾습니다. 후자가 전자보다 우선순위가 높습니다. 다음은 예제입니다.// 라이브러리에서 제공하는 config 기본값을 사용하여 인스턴스 만들기
// 이 때 timeout 값은 라이브러리의 기본값인 '0'입니다.
const instance = axios.create();
// 라이브러리에 대한 timeout 값 재정의
// 이제 모든 요청은 시간 초과 전 2.5초 대기하는 인스턴스를 사용합니다.
instance.defaults.timeout = 2500;
// 시간이 오래 걸리는 요청에 대한 timeout 값 재정의
instance.get('/longRequest', {
timeout: 5000
});
인터셉터
then 또는 catch로 처리되기 전에 요청과 응답을 가로챌 수 있다.
// 요청 인터셉터 추가하기
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);
});
나중에 필요할때 인터셉터를 제거할 수 있음.
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
커스텀 인스턴스에서도 인터셉터를 추가할 수 있다.
const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
Share article