Axios
Axios는 HTTP 요청을 위한 라이브러리로, Promise 기반으로 작동합니다. React와 같은 프레임워크에서 API 요청을 보내는 데 많이 사용되며, 브라우저뿐만 아니라 Node.js 환경에서도 호환됩니다.
Fetch API
Fetch API는 브라우저에 내장된 API로, JavaScript의 window 객체에서 바로 사용할 수 있는 HTTP 요청 도구입니다. 비동기 요청을 위해 Promise를 반환하며, 간단한 GET 및 POST 요청은 물론 다양한 HTTP 요청을 처리할 수 있습니다.
Axios는 JSON 데이터를 자동으로 변환하지만, Fetch API에서는 .json() 메서드를 호출해 수동으로 데이터를 변환해야 합니다. 또한, Fetch는 요청 성공 여부와 상관없이 then 블록을 실행하므로, 직접 응답 상태를 확인해야 합니다.
import axios from 'axios';
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) throw new Error('Network response was not ok');
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));
Axios는 객체 형태의 데이터를 전달하면 자동으로 JSON 문자열로 변환하고 적절한 헤더를 설정하지만, Fetch에서는 수동으로 JSON.stringify()를 사용하여 데이터를 변환하고 헤더를 설정해야 합니다.
axios.post('https://api.example.com/data', {
name: 'John Doe',
age: 30
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John Doe',
age: 30
})
})
.then(response => {
if (!response.ok) throw new Error('Network response was not ok');
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));
Axios는 요청 및 응답 인터셉터 기능을 제공합니다. 인터셉터는 모든 요청 또는 응답에 대해 사전 또는 사후 처리를 적용할 수 있어, 공통 헤더 설정, 토큰 갱신 등의 작업을 쉽게 수행할 수 있습니다.
axios.interceptors.request.use(config => {
config.headers.Authorization = 'Bearer my-token';
return config;
});
Axios는 HTTP 상태 코드가 200대가 아닐 경우 자동으로 catch 블록으로 넘어갑니다. 반면 Fetch는 요청이 실패해도 기본적으로 then 블록에서 처리가 이어지므로, 에러를 수동으로 확인해야 합니다.
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error('Request failed:', error));
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) throw new Error('Network response was not ok');
return response.json();
})
.catch(error => console.error('Request failed:', error));
Axios는 CancelToken을 사용하여 요청을 취소할 수 있습니다. 반면, Fetch API는 요청 취소 기능을 기본적으로 지원하지 않습니다.
// 일정 시간 후 응답이 오지 않으면 요청 취소
const cancelToken = axios.CancelToken.source();
setTimeout(() => {
cancelToken.cancel("Request timed out");
}, 5000); // 5초 후에 요청 취소
axios.get('/slow-data', { cancelToken: cancelToken.token })
.then(response => console.log(response.data))
.catch(error => {
if (axios.isCancel(error)) {
console.log("Request canceled:", error.message);
}
});
Fetch API는 브라우저 내장 기능이므로 설치가 필요 없고, 간단한 GET/POST 요청에는 충분히 유용합니다. 작은 프로젝트나 추가 기능이 필요 없는 간단한 요청에는 Fetch API를 사용하는 것이 좋습니다.
Axios는 요청/응답 인터셉터, 자동 JSON 변환, 요청 취소 등 다양한 고급 기능을 제공하므로, 인증 로직이나 요청 상태 관리가 필요한 중대형 프로젝트에서 효율적입니다.