프로젝트를 구현할 때, 주로 axios를 썼다. 하지만, fetch를 사용해보면 좋겠다는 멘토님의 말씀을 듣고 axios와 fetch의 차이에 대해 다시 공부해보았다.
Axios
1. 어떻게 설치할까?
Axios를 사용하려면 패키지 매니저를 사용하여 별도로 설치해야 한다.
2. 어떻게 사용할까?
import axios from 'axios';
axios.get('<https://example.com/api>')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
3. JSON 처리
Axios는 응답 데이터를 자동으로 JSON으로 변환한다.
import axios from 'axios';
axios.get('<https://api.example.com/data>')
.then(response => {
console.log(response.data); // 이미 JSON으로 변환됨
})
.catch(error => console.error('Axios error:', error));
4. 에러 핸들링
axios는 HTTP 상태 코드에 따라 자동으로 에러를 던진다. 에러 객체에는 요청 및 응답 정보가 포함되어 있어 디버깅이 용이하다.
import axios from 'axios';
axios.get('<https://api.example.com/data>')
.then(response => console.log(response.data))
.catch(error => {
if (error.response) {
// 서버가 응답했으나 HTTP 상태 코드가 에러 (4xx, 5xx 등)
console.error('Server error:', error.response.status, error.response.data);
} else if (error.request) {
// 요청이 서버로 전송되었지만 응답이 없음
console.error('No response received:', error.request);
} else {
// 요청 설정 중 발생한 에러
console.error('Request error:', error.message);
}
});
Fetch
1. 어떻게 설치할까?
fetch는 자바스크립트의 내장 라이브러리이다. 별도의 설치는 필요 없다.
2. 어떻게 사용할까?
fetch('<https://example.com/api>')
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
3. JSON 처리
fetch는 응답을 자동으로 JSON으로 변환하지 않는다. 응답 객체에서 .json() 메서드를 호출해야 JSON으로 파싱된다.
fetch('<https://api.example.com/data>')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // JSON 변환
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
4. 에러 핸들링
fetch는 네트워크 오류만 에러로 간주한다. 따라서, HTTP 상태 코드(404, 500 등)은 에러로 처리되지 않으며, 이를 수동으로 확인해야 한다.
fetch('<https://api.example.com/data>')
.then(response => {
if (!response.ok) {
// 수동으로 HTTP 상태 코드를 확인
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.catch(error => console.error('Error:', error));
'Javascript' 카테고리의 다른 글
| 호이스팅과 TDZ (0) | 2025.02.12 |
|---|---|
| JSON.stringify()와 JSON.parse() (1) | 2025.01.01 |
| 자바스크립트 Date 객체와 toLocaleDateString(), toLocaleString() (0) | 2024.12.31 |
| 자바스크립트 메서드와 원본 데이터 유지 (0) | 2024.12.31 |
| Ajax, V8 자바스크립트 엔진, 그리고 Node.js와의 관계 (1) | 2024.12.18 |