Axios를 간단히 소개하자면 fetch()
함수처럼 리퀘스트를 보내고 리스폰스를 받을 수 있는 라이브러리입니다. fetch()
함수랑 사용법은 비슷한데요. 조금 더 편리하게 쓸 수 있는 라이브러리라고 생각하시면 됩니다. 이번 튜토리얼에서는 Axios를 설치하고 사용하는 방법에 대해 간단히 설명드릴게요. Axios를 아주 간단하게만 사용해 볼 거니까, 쉽게 따라 하실 수 있을 겁니다.
프로젝트 폴더에서 터미널을 열고, 아래 명령어를 입력해서 axios
패키지를 설치해 주세요.
npm install axios
그럼 package.json
파일의 dependencies
안에 아래처럼 axios
가 추가될 겁니다. 참고로 버전은 조금 달라도 괜찮습니다.
"dependencies": {
...
"axios": "^1.2.2",
...
}
우선 GET
, POST
와 같은 메소드를 사용할 때, Axios에서는 간단히 점 표기법으로 axios.get()
, axios.post()
같은 함수를 사용하면 됩니다. 그리고 JSON 형식의 바디를 객체로 가져올 때 Fetch에서는 await
키워드를 사용해야 하지만, Axios에서는 그럴 필요가 없습니다.
Fetch
async function getProducts() {
const res = await fetch('https://learn.codeit.kr/api/codeitmall/products/');
const products = await res.json();
return products;
}
Axios
async function getProducts() {
const res = await axios.get('https://learn.codeit.kr/api/codeitmall/products/');
const products = res.data;
return products;
}
body
라는 객체를 파라미터로 받아서 리퀘스트를 보내는 예시입니다.
Fetch
async function createSizeReview(body) {
const res = await fetch(
'https://learn.codeit.kr/api/codeitmall/size-reviews/',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
}
);
const newSizeReview = await res.json();
return newSizeReview;
}
Axios
async function createSizeReview(body) {
const res = await axios.post(
'https://learn.codeit.kr/api/codeitmall/size-reviews/',
body
);
const newSizeReview = res.data;
return newSizeReview;
}
Fetch에서는 쿼리 문자열을 직접 만들어서 넣어야 하는데요. Axios에서는 params
라는 속성의 객체로 전달하면 됩니다.
Fetch
async function getProducts({ offset = 0, limit = 10 }) {
const url = `https://learn.codeit.kr/api/codeitmall/products?offset=${offset}&limit=${limit}`
const query = new URLSearchParams({ offset, limit });
const res = await fetch(url);
const products = await res.json();
return products;
}
Axios
async function getProducts({ offset = 0, limit = 10 }) {
const res = await axios.get('https://learn.codeit.kr/api/codeitmall/products/', {
params: { offset, limit },
});
const products = res.data;
return products;
}
리퀘스트를 보낼 때 공통으로 사용하는 주소나 헤더가 있기 마련입니다. 이럴 때는 인스턴스를 만들면 반복되는 코드를 줄일 수 있습니다. 예를 들어서 아래 예시는 axios.js
파일에 axios.create()
함수를 사용해서 Axios 인스턴스를 만든 예시입니다. baseURL
을 지정해서 반복되는 코드를 줄였습니다.
/lib/axios.js
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://learn.codeit.kr/api/codeitmall/'
});
export default instance;
/pages/index.js
import axios from './lib/axios';
// ...
async function getProducts() {
const res = await axios.get('/products/');
const products = res.data;
return products;
}
async function createSizeReview(body) {
const res = await axios.post('/size-reviews/', body);
const newSizeReview = res.data;
return newSizeReview;
};