
[^1.6.5] 버전
Axios는 JavaScript 환경에서 사용되는 HTTP 클라이언트 라이브러리로, 주로 브라우저와 Node.js 환경에서 HTTP 요청을 수행하는 데 사용된다. Axios는 Promise 기반의 API를 제공하며, 비동기적인 HTTP 요청을 쉽게 처리할 수 있다.
Promise 기반 API
Axios는 ES6의 Promise 기반 API를 사용하여 비동기적인 요청을 처리한다. 이를 통해 콜백 지옥을 피하고 코드를 더 간결하게 작성할 수 있다.
브라우저와 Node.js 지원
Axios는 브라우저 및 Node.js 환경에서 모두 사용할 수 있다. 이는 클라이언트 측과 서버 측에서 동일한 코드를 사용하여 HTTP 요청을 수행할 수 있음을 의미한다.
요청과 응답 변환
Axios는 요청과 응답을 변환할 수 있는 기능을 제공한다. 이를 통해 요청 및 응답 데이터를 자동으로 변환하거나 수정할 수 있다. JSON, XML 등의 형식으로 데이터를 변환할 수도 있다.
HTTP 요청 메서드 지원
Axios는 다양한 HTTP 요청 메서드(GET, POST, PUT, PATCH, DELETE 등)를 지원한다.
요청과 응답 인터셉터
Axios는 요청과 응답에 대한 인터셉터(interceptor)를 제공하여 요청이나 응답 전에 수행되는 작업을 정의할 수 있다. 예를 들어, 특정 토큰을 헤더에 추가하거나 오류 처리를 수행할 수 있다.
취소 기능
Axios는 요청을 취소하는 기능을 제공한다. 이는 요청이 아직 완료되지 않았을 때 요청을 중단할 수 있도록 해준다.
import React, { useState, useEffect, type FC } from 'react';
import axios, { AxiosResponse, AxiosError } from 'axios';
// Post 데이터의 타입 정의
type Post {
userId: number;
id: number;
title: string;
body: string;
}
const Example: FC = () => {
const [data, setData] = useState<Post | null>(null);
const [isLoading, setIsLoading] = useState<boolean>(false);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
setIsLoading(true);
// Axios를 이용한 HTTP GET 요청
axios.get<Post>('https://jsonplaceholder.typicode.com/posts/1')
.then((res: AxiosResponse<Post>) => {
setData(re.data); // 성공 시 데이터 설정
})
.catch((err: AxiosError) => {
setError(new Error(err.message)); // 실패 시 에러 설정
}).filnally(() => {
setIsLoading(false);
});
}, []); // 빈 배열은 컴포넌트가 마운트될 때 한 번만 실행되도록 보장
if (isLoading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error.message}</p>;
}
return (
<div>
<h1>React Axios Example</h1>
<p>Data from server: {data?.title}</p>
</div>
);
};
export default Example;
위의 코드에서, 더미 데이터를 서버에서 받아오기 위해 jsonplaceholder라는 더미 API를 호출해서 가져온 뒤, Post라는 타입을 사용하여 데이터의 구조를 정의하였다. 받아올 response타입을 axios.get<Type> 으로 지정할 수 있다. 또한 Axios에서 반환되는 응답과 에러 객체의 타입도 정의하여 명시적인 타입 검사를 수행하도록 하였다. 이렇게 함으로써 코드의 안정성을 높일 수 있다.
const axios = require('axios');
// 지정된 ID를 가진 유저에 대한 요청
axios.get('/user?ID=12345')
.then((response) => {
// 성공 핸들링
console.log(response);
})
.catch((error) => {
// 에러 핸들링
console.log(error);
})
.finally(() => {
// 항상 실행되는 영역
});
// parameter 옵션을 통해 요청할 수도 있다. (= axios.get('/user?ID=12345')) 와 같다.
axios.get('/user', {
params: {
ID: 12345
}
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
})
.finally(() => {
// 항상 실행되는 영역
});
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
이제, axios의 주요 메서드와 사용법, 여러 옵션들을 다음 포스트에서 살펴보자.