기본적인 Axios VS Fetch 코드 차이
fetch https://github.com/dancinncoder/api-contracts
axios https://github.com/dancinncoder/api-contracts/tree/axios
Fetch
ES6부터 도입된 Javascript 내장 라이브러리이다. Promise 기반 비동기 통신을 할 수 있게한다.
단점
- 미지원 브라우저 존재
- 개발자에게 불친절한 response (axios는 response가 json 포맷으로 제공, fetch는 response.json() 작업을 해줘야함)
- axios에 비해 부족한 기능 (에러처리)
에러처리 비교
axios
- axios.get() 요청이 반환하는 Promise 객체가 갖고 있는 상태코드가 2XX의 범위를 넘어감녀 거부(reject)를 한다. 따라서 곧바로 그런 경우는 catch() 부분을 통해 에러핸들링이 가능하다
더보기
const url = "https://jsonplaceholder.typicode.com/todos";
// axios 요청 로직
axios
.get(url)
.then((response) => console.log(response.data))
.catch((err) => {
// 오류 객체 내의 response가 존재한다 = 서버가 오류 응답을 주었다
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);
}
});
하지만 fetch는 catch() 부분이 발생하는 경우는 오직 네트워크 장애 케이스다. 따라서 개발자가 then()안에 모든 케이스에 대한 HTTP 에러 처리를 해야 하는 불편한 점이 있다.
더보기
const url = "~~~";
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);
});
728x90
반응형
'부트캠프 개발일지 2023-2024 > React 리액트' 카테고리의 다른 글
[10주차] 리액트심화: React Query 이론과 개념 (2) | 2023.12.06 |
---|---|
[9주차] 리액트심화: interceptor, instance, .env (0) | 2023.11.29 |
[9주차] 리액트심화: 비동기 통신 axios(post, delete,patch) 하기 (0) | 2023.11.28 |
[9주차] 리액트심화: 비동기 통신 axios(get) 하기 (1) | 2023.11.28 |
[9주차] 리액트심화: HTTP, URL, 상태코드 (1) | 2023.11.28 |