💡 딥다이브 주제
[데이터 통신] Axios와 Fetch API의 차이점을 비교하고, 실제 프로젝트에서 각각을 어떤 상황에 사용하는 것이 적합한지 설명하세요.
Axios와 Fetch API는 웹 애플리케이션에서 서버와 데이터를 주고받기 위해 사용하는 HTTP 요청 라이브러리.
모두 Promise 기반의 비동기 요청 방식을 사용
npm install axiosfetch('http://localhost:4444/hello');
fetch("http://localhost:4444/posts", {
method: "POST", // POST
headers: { // 헤더 조작
"Content-Type": "application/json",
},
body: JSON.stringify({ // 보낼 데이터 본문은 body에 할당
title: "Test",
body: "I am testing!",
userId: 1,
}),
})
axios('http://localhost:4444/hello');
axios("http://localhost:4444/posts", {
method: "get", // 다른 옵션도 가능합니다 (post, put, delete, etc.)
headers: {},
data: {}, // 보낼 데이터 본문은 data에 할당
});
axios.get(url, {
// 설정 옵션
});
GET으로 받아온 응답 처리 비교
response.json()
fetch("http://localhost:4444/posts")
.then((response) => response.json())
.then((data) => console.log(data));
data 프로퍼티에서 사용할 수 있다.axios.get("http://localhost:4444/posts")
.then((response) => console.log(response.data));
데이터를 전송하는 post 요청을 해보자.
JSON.stringify() : JSON객체를 문자열로 변환한 뒤 body에 할당해야 한다.const todo = {
title: "A new todo",
completed: false,
};
fetch("https://jsonplaceholder.typicode.com/todos", {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(todo),
})
.then((response) => response.json())
.then((data) => console.log(data));
data 프로퍼티에 할당한다. 개발자가 직접 문자열로 변환할 필요없다. Axios가 자동으로 데이터를 문자열로 변환해준다.const todo = {
title: "A new todo",
completed: false,
};
axios
.post("https://jsonplaceholder.typicode.com/todos", {
headers: {
"Content-Type": "application/json",
},
data: todo,
})
.then(console.log);
Fetch는 네트워크 오류가 없으면 네트워크 요청을 성공했다고 판단. (상태코드와 무관)
즉, 네트워크 연결이 제대로 되어 서버로부터 응답이 왔다면, 그 응답이 200번대인지, 400번대, 500번대인지 상관없이 요청이 “성공적으로 완료”된 것으로 간주한다.
4xx, 5xx 상태코드가 반환되어도 fetch()는 reject되지 않고 응답 객체를 resolve 한다.
HTTP 에러 코드가 있어도 catch로 잡히지 않는다.
따라서 개발자 도구를 통해 ok속성이나 직접 상태코드를 확인해야 한다.
(ok 속성이 true 이면 2xx라는 뜻. false이면 2xx대가 아님을 의미.)
예시코드
const url = "https://jsonplaceholder.typicode.com/todos";
fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error(
`This is an HTTP error: The status is ${response.status}`
);
}
return response.json();
})
.then(console.log)
.catch((err) => {
console.log(err.message);
});
catch 블록에서 처리할 수 있도록 한다..catch((err) => {
// 에러 처리
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);
}
});HTTP 클라이언트에서 요청 시간이 초과될 경우 어떻게 처리하는지 알아보자.
Axios에서는 타임아웃을 쉽게 설정할 수 있다. 요청을 보낼 때 timeout 옵션을 추가하면 된다.
axios.get('https://example.com/api', {
timeout: 5000 // 타임아웃을 5000ms (5초)로 설정
})
.then(response => {
console.log(response.data);
})
Fetch API에는 기본적으로 타임아웃 기능이 없어서, 직접 구현해야 한다. (AbortController를 사용해야 함.)
| axios | fetch | |
|---|---|---|
| 설치여부 | 따로 라이브러리 설치 필요 | 현대 브라우저에 빌트인이라 설치 필요 없음 |
| 형식변환 | 자동으로 형식 변환 | .json() 와 .stringify() 를 사용해 변환해주는 과정 필요 |
| 타임아웃 | 요청취소가능, 타임아웃 쉽게 설정 가능 | 타임아웃 기능 없음. |
| 에러처리 | 2xx 이외의 상태코드는 에러로 처리. 상태코드별 에러처리 편리. | 네트워크 에러만 요청실패로 간주. 4xx, 5xx 상태코드도 성공으로 간주. 에러처리 불편. |
| 브라우저 | 다양한 브라우저 지원 | 지원되지 않는 브라우저가 있음 |
프로젝트에서 어떤 방법을 선택할 지는 개인의 선호도와 사용 편의성에 따라 달라진다.
axios는 별도의 설치가 필요하다는 단점이 있다. 하지만, fetch보다 더 많은 기능을 지원하고 문법이 조금이나마 간소화 된다는 장점이 있다.
간단하게 사용할때는 별도의 설치가 필요없는 fetch를 사용하고, 확장성을 염두했을 땐 axios를 쓰는것이 좋을것이라 생각한다.