프론트엔드와 DB를 직접 연결할 수는 있지만 보안적으로 크리티컬 하다는 문제가 있다. 따라서 프론트엔드와 데이터베이스를 직접 연결하는 방식이 아닌, 백엔드와의 통신을 통해 데이터에 접근해야 한다. 이를 구현하기 위한 방법에는 여러가지가 있지만 REST API를 사용한 방법 중 하나인 Fetch API와 Axios에 대해 간단히 비교해보자.
간단히 콘솔창에 API로 가져온 데이터를 출력해보자. (The Star Wars API 사용)
Fetch API는 브라우저에 내장되어 있기 때문에 별도로 설치할 필요가 없다. fetchMovies는 다음과 같이 구현할 수 있다.
const fetchMovies = async () => {
try {
const response = await fetch('https://swapi.dev/api/films/')
if (!response.ok) {
throw new Error('response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('error:', error.message);
}
};
먼저 npm 이나 yarn 으로 Axios를 설치 후, axios
를 import 한다.
import axios from 'axios';
그 다음 fetchMovies는 다음과 같이 구현할 수 있다.
const fetchMovies = async () => {
try {
const response = await axios.get('https://swapi.dev/api/films/');
const data = response.data;
console.log(data);
} catch (error) {
console.error('error:', error.message);
}
};
POST를 사용해서 데이터를 전송해보자 (REQRES API 사용)
const createUser = async (name, job) => {
try {
const response = await fetch("https://reqres.in/api/users", {
method: "POST",
body: JSON.stringify({
name: name,
job: job
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
});
if (!response.ok) {
throw new Error("res was not ok");
}
const data = await response.json();
console.log(data);
} catch (error) {
console.log(error.message);
}
};
성공적으로 POST가 성공적인 경우 콘솔창에 다음과 같이 출력된다.
{
name: "eunjios",
job: "student",
id: "751",
createdAt: "2023-10-09T05:21:20.957Z"
}
const createUser = (name, job) => {
try {
const response = await axios.post("https://reqres.in/api/users", {
name: name,
job: job
});
console.log(response.data);
} catch (error) {
console.error(error.message);
}
};
Note how we supply a standard Javascript object as data when sending Axios POST requests (including PUT and PATCH requests). By default, Axios converts Javascript data to JSON (including AJAX). The "content-type" header is also set to “application/json.”
Axios는 POST 요청 header의 content-type이 기본적으로 "application/json" 이므로 헤더를 명시할 필요가 없다.
Axios 역시 콘솔창에 다음과 같이 출력된다.
{
name: "eunjios",
job: "student",
id: "751",
createdAt: "2023-10-09T05:21:20.957Z"
}
FETCH | AXIOS | |
---|---|---|
패키지 설치 | 브라우저에 내장됨 설치 X | third-party 패키지 설치 O |
데이터 속성 | .body 사용 | .data 사용 |
데이터 타입 | Fetch의 body 는 문자열로 변환 필요 | Axios의 data 는 객체를 포함 |
요청 수락 조건 | response 객체에 ok 속성이 있을 경우 | status 200, statusText가 'OK'인 경우 |
JSON 데이터 처리 | .json() 메서드 사용 | 자동 |
요청 취소 및 시간 초과 | 미지원 | 지원 |
다운로드 진행률 | 미지원 | 지원 |
브라우저 호환성 | Chrome 42+ Firefox 39+ Edge 14+ Safari 10.1+ | 더 다양한 브라우저 지원 |
성능적인 측면에서는 Fetch API가 조금 더 빠르다고 하는데, 비동기 처리기 때문에 큰 의미는 없다고 한다. 그렇다면 여러 측면에서 더 편리하게 쓸 수 있는 Axios를 사용하는 것이 이득이 아닐까 싶다 🤔
Axios 관련 자세한 내용은 이 포스트 를 참고하면 좋을 것 같다.