fetch & axios
먼저 두가지에 대해서 간략한 설명을 하고 비교를 해보며 학습을 해보겠습니다.
- Fetch API는 네트워크 요청을 위해 fetch()라는 메서드를 제공하는 인터페이스입니다. 모던 브라우저에 내장되어 있어 따로 설치할 필요가 없습니다.
- Axios는 서드파트 라이브러리로 CDN 혹은 패키지 매니저를 통해 설치하여야 사용할 수 있습니다.
- 두 가지 모두 promise 기반의 HTTP 클라이언트입니다. 즉, 네트워크를 요청하면 resolve, reject 할 수 있는 promise를 반환합니다.
두 가지는 모두 네트워크 요청을 하고 promise를 반환합니다. 무엇이 다를까요?
문법
1) fetch
fetch(url, {
method: "GET", // 다른 옵션도 가능합니다 (POST, PUT, DELETE, etc.)
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
});
https://jsonplaceholder.typicode.com/guide/ ( 여기서 다양한 fetch 사용법을 볼 수 있어요 )
JSONPlaceholder - Guide
Guide Below you'll find examples using Fetch API but you can JSONPlaceholder with any other language. You can copy paste the code in your browser console to quickly test JSONPlaceholder. Getting a resource fetch('https://jsonplaceholder.typicode.com/posts/
jsonplaceholder.typicode.com
2) axios
axios.get(url, {
// 설정 옵션
});
// or
axios({
method: "get",
url: url,
headers: {},
data: {},
}); // method를 주지 않으면 기본적으로 "get" 메소드로 처리
axios는 두가지 표현식으로 사용이 가능합니다.
문자열 변환
우리는 데이터를 전송하기 위해서는 JSON문자열로 직렬화해야 합니다. POST 메소드로 fetch 와 axios코드를 작성해보겠습니다.
1) fetch
const url = "https://jsonplaceholder.typicode.com/todos";
const todo = {
title: "A new todo",
completed: false,
};
fetch(url, {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(todo),
})
.then((response) => response.json())
.then((data) => console.log(data));
2) axios
const url = "https://jsonplaceholder.typicode.com/todos";
const todo = {
title: "axios is auto stringfy",
completed: false,
};
axios
.post(url, {
headers: {
"Content-Type": "application/json",
},
data: todo,
})
.then(console.log);
axios는 todo 를 그냥 보내면 되지만 fetch는 JSON.stringify 과정이 필요하다.
JSON데이터 처리
1) fetch
const url = "<https://jsonplaceholder.typicode.com/todos>";
fetch(url)
.then((response) => response.json())
.then(console.log);
fetch()는 .then() 메서드에서 처리된 promise를 반환합니다. 이 때는 아직 우리가 필요한 JSON 데이터의 포맷이 아니기 때문에 응답 객체의 .json() 메서드를 호출합니다. 그러면 JSON 형식의 데이터로 이행(resolve)된 또 다른 promise를 반환합니다.
2) axios
const url = "<https://jsonplaceholder.typicode.com/todos>";
axios.get(url).then((response) => console.log(response.data));
axios는 기본적으로 JSON타입으로 사용으로, 응답 데이터는 언제나 응답 객체의 data 프로퍼티에서 사용하고 다음과 같이 옵션으로 응답 타입을 재정의가 가능합니다.
에러 처리
axios와 fetch 모두 promise를 반환합니다. promise는 .catch()를 사용하여 에러를 핸들링합니다.
두개의 차이는 코드를 보며 설명하겠습니다.
먼저, axios 코드입니다.
const url = "<https://jsonplaceholder.typicode.com/todos>";
axios
.get(url)
.then((response) => console.log(response.data))
.catch((err) => {
console.log(err.message);
});
Axios의 promise는 상태코드가 2xx의 범위를 넘어가면 거부(reject)합니다. 에러 객체에 응답(response) 또는 요청(request) 프로퍼티가 포함되어 있는지 확인하여 에러에 대한 자세한 정보를 확인할 수 있습니다.
따라서 에러처리가 좀더 간편해집니다.
if (err.response) {
// 요청이 이루어졌고 서버가 응답했을 경우
const { status, config } = err.response;
if (status === 404) {
console.log(`${config.url} not found`);
}
if (status === 500) {
console.log("Server error");
}
} else if (err.request) {
// 요청이 이루어졌으나 서버에서 응답이 없었을 경우
console.log("Error", err.message);
} else {
// 그 외 다른 에러
console.log("Error", err.message);
}
위와 같이 error프로퍼티를 통해 에러 처리를 확실히 할 수 있습니다.
하지만 fetch는 다릅니다. then 절을 사용해 수동으로 HTTP 에러를 핸들링합니다.
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
// 처리된 데이터
})
.catch(error => {
// 네트워크 에러 또는 데이터 처리 에러
console.error('Fetch Error:', error);
});
이렇게 catch로 바로 보내지 못하고 알아서 어떤 에러인지를 잡아줘야 합니다.
정리
axios는 native fatch보다 속도가 살짝 더 느립니다만, 비동기 클라이언트에서 속도는 크게 중요치 않습니다.
하지만 에러 핸들링, 응답 시간 초과/ 요청 취소 , JSON데이터 다루기 등에서 편한점이 많아 axios를 많이 사용합니다.