![[React] Axios 사용법 [6/5 study]](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdna%2FDDGwc%2FbtsHYU5ajm6%2FAAAAAAAAAAAAAAAAAAAAAG2QxRNt40bPEW_pWspLioorqULOSxQ304nQEFiA5nBY%2Fimg.png%3Fcredential%3DyqXZFxpELC7KVnFOS48ylbz2pIh7yKj8%26expires%3D1759244399%26allow_ip%3D%26allow_referer%3D%26signature%3DJHa1DEUy0p%252FzFpEaNE6%252Fo7bhhuY%253D)
Axios 사용법
❗️소개
Axios를 간단히 소개하자면 fetch() 함수처럼 리퀘스트를 보내고 리스폰스를 받을 수 있는 라이브러리입니다!
fetch() 함수랑 사용법은 비슷한데요.
조금 더 편리하게 쓸 수 있는 라이브러리라고 생각하시면 됩니다.
Axios를 설치하고 사용하는 방법에 대해 간단히 설명드릴게요. Axios를 아주 간단하게만 사용해 볼 거니까, 쉽게 따라 하실 수 있을 겁니다.
❗️Axios 설치방법
npm install axios
package.json 파일의 dependencies 안에 아래처럼 axios 가 추가될 겁니다.
"dependencies": {
...
"axios": "^1.2.2",
...
}
❗️Fetch와 Axios 사용법 비교
- 요약
1. 우선 GET, POST와 같은 메소드를 사용할 때, Axios에서는 간단히 점 표기법으로 axios.get(), axios.post() 같은 함수를 사용하면 됩니다.
2. JSON 형식의 바디를 객체로 가져올 때 Fetch에서는 await 키워드를 사용해야 하지만, Axios에서는 그럴 필요가 없습니다.
❗️GET 예시
Fetch
async function getProducts() {
const res = await fetch('API 주소');
const products = await res.json();
return products;
}
Axios
async function getProducts() {
const res = await axios.get('API 주소');
const products = res.data;
return products;
}
쉽죠?
❗️POST 예시
body라는 객체를 파라미터로 받아서 리퀘스트를 보내는 예시입니다!!
Fetch
async function createSizeReview(body) {
const res = await fetch(
'API 주소',
{
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(
'API 주소',
body
);
const newSizeReview = res.data;
return newSizeReview;
}
더 간략해 져서 보기 좋네요!
❗️쿼리 문자열 예시
Fetch에서는 쿼리 문자열을 직접 만들어서 넣어야 하는데요. Axios에서는 params라는 속성의 객체로 전달하면 됩니다.
Fetch
async function getProducts({ offset = 0, limit = 10 }) {
const url = `API주소/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('API 주소/products/', {
params: { offset, limit },
});
const products = res.data;
return products;
}
훨씬 더 간단하지 않나요?
❗️Axios 인스턴스 활용하는법
리퀘스트를 보낼 때 공통으로 사용하는 주소나 헤더가 있기 마련입니다.
이럴 때는 인스턴스를 만들면 반복되는 코드를 줄일 수 있습니다.
예를 들어서 아래 예시는 axios.js 파일에 axios.create() 함수를 사용해서 Axios 인스턴스를 만든 예시입니다.
baseURL을 지정해서 반복되는 코드를 줄였습니다.
파일 경로
/lib/axios.js
import axios from 'axios';
const instance = axios.create({
baseURL: 'API 주소'
});
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;
};
이렇게 하면 반복되는 코드가 많이 줄겠네요!
🔥마무리
Axios 라이브러리는 이번에 진행한 첫 프로젝트 에서도 사용했는데요! 너무 편해서 추천드리고 싶습니다!
오늘도 화이팅!
프론트엔드 공부일지 입니다.
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!