1차 프로젝트때는 fetch로 backend와 통신을 했다. 2차때는 Axios 사용을 위해 미리 공부해보자.
브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리
크로스브라우징에 최적화 되어있다.
npm install axios
const axios = require('axios');
// ID로 사용자 요청
axios.get('/user?ID=12345')
// 응답(성공)
.then(function (response) {
console.log(response);
})
// 응답(실패)
.catch(function (error) {
console.log(error);
})
// 응답(항상 실행)
.then(function () {
// ...
});
4번째 줄의 axios.get은 아래와 같이 쓸 수 있다
axios.get('/user', {
params: {
ID: 12345
}
})
Async/Await를 사용해 비동기 통신을 요청 할 수 있다.
오류 디버깅을 위해 try...catch문을 사용한다.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
아래와 같은 방식으로 사용 가능하다.
axios({
method: 'post',
url: '/user'
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
})
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));
여러개의 요청을 동시 수행하기 위해서 axios.all 메서드를 사용한다.
요청에 따른 응답 결과에는 다음과 같은 정보가 담겨있다.
{
// `data`는 서버가 제공한 응답(데이터)입니다.
data: {},
// `status`는 서버 응답의 HTTP 상태 코드입니다.
status: 200,
// `statusText`는 서버 응답으로 부터의 HTTP 상태 메시지입니다.
statusText: 'OK',
// `headers` 서버가 응답 한 헤더는 모든 헤더 이름이 소문자로 제공됩니다.
headers: {},
// `config`는 요청에 대해 `axios`에 설정된 구성(config)입니다.
config: {},
// `request`는 응답을 생성한 요청입니다.
// 브라우저: XMLHttpRequest 인스턴스
// Node.js: ClientRequest 인스턴스(리디렉션)
request: {}
}
then
으로 다음과 같이 응답을 받을 수 있다.
axios.get('/user/12345')
.then(function (response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});