
Node.js 플랫폼에서 모두 사용 가능XHR(XMLHttpRequest) 요청 가능CSRF(크로스-사이트 요청 위조 공격) 보호 기능이 내장되어 있다.// npm에서 설치
npm install axios
// yarn에서 설치
yarn add axios
또는 단순하게 CDN을 로드해서 사용이 가능하다.
axios 객체는 아래와 같이 간단하게 HTTP 요청을 할 수 있다.
axios({
url: 'http://localhost:3042/public/Data/OrderTableData.json',
method: 'get',
headers: {
Authorization: localStorage.getItem("access_token"),
},
})
그러나 보기 명확하게 method를 분리하여 사용할 수도 있다.
Axios가 아직 인기있는 라이브러리는 아니지만 HTTP 요청에서 사용하는 다양한 method도 제공하고 있다.
그리고 HTTP 헤더를 가져와서 본문을 삭제하는 방법 또한 제공한다.
Axios를 사용하는 편한 방법 중 하나는 Modern JavaScript의 요소인 async/await 구문을 사용하는 것이다.
이 Node.js 예제는 Dog API를 사용해서 모든 Dog의 breed 목록을 가져와서 axios.get() 한다.
const axios = require('axios');
const getBreeds = async () => {
try {
return await axios.get('http://dog.ceo/api/breeds/list/all');
} catch (error) {
console.error(error);
}
};
const countBreeds = async () => {
const breeds = await getBreeds();
if (breeds.data.message) {
console.log(`현재 강아지의 수는 ${Object.entries(breeds.data.message)
}
};
countBreeds();
// Object.entries() 메서드는 for...in와 같은 순서로 주어진 객체 자체의 enumerable 속성 [key, value] 쌍의 배열을 반환합니다.
const object1 = {
a: 'somestring',
b: 42
};
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
// expected output:
// "a: somestring"
// "b: 42"
// order is not guaranteed
만약 async / await 구문을 사용하지 않는다면 Promise 구문을 사용 할 수 있다.
const axios = require('axios');
const getBreeds = () => {
try {
return axios.get('https://dog.ceo/api/breeds/list/all');
} catch (error) {
console.error(error)
}
};
const countBreeds = () => {
const breeds = getBreeds()
.then(response => {
if (response.data.message) {
console.log(`현재 강아지의 수는 ${Object.entries(breeds.data.message).length}입니다.`);
}
})
.catch(error -> {
console.log(error);
})
};
GET 응답에는 URL에 매개변수가 포함 될 수 있다.
https://text.com/?foo=bar
Axios를 사용하여 GET 요청시 간단하게 매개변수를 추가 할 수 있다.
axios.get('https://text.com/?foo=bar');
또는 params 옵션에서 추가하여 사용 할 수 있다.
axios.get('https://test.com/', {
params: {
foo: 'bar'
}
});
axios.post 처럼 POST 요청은 axios.get GET 요청과 거의 같다.
axios.post('https://test.com');
POST 역시 매개변수를 추가하는 방법은 GET과 같다.
axios.post('https://test.com/', {
params: {
foo: 'bar'
}
});
순수 자바스크립트를 사용하는 것으로도 매우 간단하게 api 통신이 가능하지만, axios의 장점을 생각하면서 도입을 권장합니다.