
node.js와 브라우저를 위한 Promise 기반 HTTP 클라이언트
브라우저를 위해 XML HttpRequests 생성
node.js를 위해 HTTP 요청 생성
Promise API 지원
요청 및 응답 인터셉트
요청 및 응답 데이터 변환
요청 취소
JSON 데이터 자동 변환
XSRF를 막기위한 클라이언트 사이드 지원
npm 사용하여 설치
npm install axios
bower 사용하여 설치
bower install axios
yarn 사용하여 설치
yarn add axios
CDN 사용하여 설치
<!-- jsDelivr -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<!-- unpkg -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
require() 이용한 CommonJS를 사용하는 동안 타입스크립트 타이핑을 사용하려면 다음 방법을 사용하자.
const axios = require('axios').default;
GET 요청 수행하기
const axios = require('axios');
// 지정된 ID를 가진 유저에 대한 요청
axios.get('/user?ID=12345')
.then(function (response) {
// 성공 핸들링
console.log(response);
})
.catch(function (error) {
// 에러 핸들링
console.log(error);
})
.finally(function () {
// 항상 실행되는 영역
});
// 선택적으로 위의 요청은 다음과 같이 수행될 수 있습니다.
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(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);
});
여러 동시 POST 요청 생성
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
Promise.all([getUserAccount(), getUserPermissions()])
.then(function (results) {
const acct = results[0];
const perm = results[1];
});
axios에 해당 config을 전송하면 요청이 가능하다.
// POST 요청 전송
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
// node.js에서 GET 요청으로 원격 이미지 가져오기
axios({
method: 'get',
url: 'http://bit.ly/2mTM3nY',
responseType: 'stream'
})
.then(function (response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
이렇게 간단하게 Axios에 대해 알아보았다.
Axios는 비동기 통신 라이브러리 중 가장 많이 사용하는 라이브러리로서
실무에서도 굉장히 많이 사용되고 있다.
이 글을 보면서 도움이 되었으면 좋겠다.