| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
- Next.js
- 개발일지
- 서버 컴포넌트
- js
- 다시 홧팅
- HTML
- 백준
- 바닐라JS
- git flow finish
- JavaScript
- freecodecamp
- 클라이언트 컴포넌트
- 힘들었던 한주
- axios
- 끝까지 잘 마무리하기
- git
- CSS
- javascript30
- 실무는 공식문서로
- git flow start
- 공부할 거 넘많다~
- AJAX
- api 라우트
- TS
- fetch pull 차이
- jQuery
- 책으론 원리만
- 차이점
- Main
- Mac
- Today
- Total
다다의 개발일지 6v6
Axios 에 대해 알아보자! 본문
Axios란?
Axios는 HTTP 요청을 쉽게 보낼 수 있도록 도와주는 자바스크립트 라이브러리
REST API와 통신할 때 사용되며, Promise 기반의 비동기 HTTP 요청을 쉽게 관리할 수 있음.
✅ 주요 특징
✔ Promise 기반 → async/await 사용 가능
✔ 자동 JSON 변환 → 응답 데이터를 JSON으로 자동 변환
✔ 요청 & 응답 인터셉터 지원 → 요청 전/후 데이터를 가공 가능
✔ 취소 기능 → 요청을 중간에 취소 가능
✔ 타임아웃 설정 → 일정 시간 동안 응답이 없으면 자동으로 요청 취소
✔ 브라우저 & Node.js 환경에서 사용 가능
Axios 기본 사용법
1️⃣ GET 요청
import axios from "axios";
axios.get("https://jsonplaceholder.typicode.com/posts/1")
.then(response => console.log(response.data))
.catch(error => console.error(error));
✅ 응답 데이터는 response.data에 저장됨
2️⃣ POST 요청 (데이터 보내기)
axios.post("https://jsonplaceholder.typicode.com/posts", {
title: "Axios 연습",
body: "Axios는 정말 유용함",
userId: 1
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
✅ 서버로 데이터를 JSON 형식으로 보냄!
3️⃣ PUT 요청 (데이터 수정)
axios.put("https://jsonplaceholder.typicode.com/posts/1", {
title: "수정된 제목",
body: "내용이 수정되었습니다.",
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
✅ PUT은 기존 데이터를 덮어씀! (부분 수정은 PATCH 사용)
4️⃣ DELETE 요청 (데이터 삭제)
axios.delete("https://jsonplaceholder.typicode.com/posts/1")
.then(response => console.log("삭제 완료!"))
.catch(error => console.error(error));
✅ 삭제 요청을 보낼 수 있음!
Axios vs Fetch 비교
| Axios | Fetch | |
| 요청 방식 | axios.get(), axios.post() 등 제공 | fetch() 사용 |
| 응답 데이터 | 자동 JSON 변환 (response.data) | response.json()을 호출해야 함 |
| 요청 취소 | axios.CancelToken으로 가능 | 기본적으로 지원 안함 |
| 타임아웃 설정 | 기본 제공 (timeout: 5000) | 직접 setTimeout()을 구현해야 함 |
| 인터셉터 지원 | 요청 및 응답을 가로채서 수정 가능 | 직접 fetch()를 래핑해야 가능 |
| 오류 처리 | HTTP 에러 상태코드(400, 500)를 자동으로 처리 | 명시적으로 response.ok 확인 필요 |
| 브라우저 지원 | 최신 브라우저와 Node.js 모두 지원 | 브라우저 내장 API, Node.js에서 추가 설정 필요 |
✅ Axios가 fetch보다 편리한 점
- JSON 변환을 자동으로 해줌
- 요청 & 응답 인터셉터 기능 제공
- 요청 취소 기능 제공
요청 & 응답 인터셉터
인터셉터를 사용하면 요청을 보내기 전, 응답을 받기 전에 데이터를 가공할 수 있다!
1. 요청 인터셉터
- 서버에 데이터를 보내기 전에 추가 작업(예: 인증 토큰 추가)을 수행할 수 있음
- 이런 식으로 요청 보내기 전에 토큰 추가하면 됨!
-
if (token && config.headers) {config.headers.Authorization = `Bearer ${token}`;}
- const token = localStorage.getItem("authToken");
axios.interceptors.request.use((config) => {
config.headers.Authorization = 'Bearer token'; // 헤더에 토큰 추가
return config;
}, (error) => {
return Promise.reject(error);
});
2. 응답 인터셉터
- 서버로부터 응답을 받은 후 데이터를 처리하거나 에러를 처리
axios.interceptors.response.use((response) => {
return response;
}, (error) => {
if (error.response.status === 401) {
console.error('Unauthorized!');
}
return Promise.reject(error);
});
✅ 인터셉터를 활용하면 토큰 추가, 에러 처리 등을 쉽게 할 수 있음
Axios를 이용한 효율적인 데이터 관리
1️⃣ 반복되는 요청을 커스텀 훅으로 관리
2️⃣ 요청 & 응답 인터셉터로 공통 로직 처리 (ex. 토큰 자동 추가)
3️⃣ 취소 토큰을 이용해 불필요한 요청 방지
4️⃣ 응답 캐싱을 통해 성능 최적화
Axios 설치 및 기본 사용법
설치
Axios는 npm이나 CDN을 통해 설치할 수 있습니다.
# npm으로 설치
npm install axios
기본 사용법
1. GET 요청
import axios from 'axios';
axios.get('https://api.example.com/data')
.then((response) => {
console.log(response.data); // 서버로부터 받은 데이터
})
.catch((error) => {
console.error('Error fetching data:', error);
});
2. POST 요청
axios.post('https://api.example.com/data', {
name: 'John Doe',
age: 30
})
.then((response) => {
console.log('Data saved:', response.data);
})
.catch((error) => {
console.error('Error saving data:', error);
});
3. async/await를 활용한 비동기 요청
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/data');
console.log(response.data);
} catch (error) {
console.error('Error:', error);
}
};
fetchData();
Axios의 주요 옵션
axios({
method: 'post', // HTTP 메서드 (GET, POST, PUT, DELETE 등)
url: 'https://api.example.com', // 요청 URL
data: { // 요청 데이터 (POST, PUT 등)
name: 'John Doe',
age: 30
},
headers: { // 요청 헤더
'Authorization': 'Bearer token'
},
params: { // URL 파라미터
id: 123
},
timeout: 5000 // 요청 제한 시간 (밀리초 단위)
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
Axios vs Fetch API
Axios는 HTTP 요청을 간편화하고 데이터 송수신 및 처리 과정에서 많은 편의 기능을 제공한다. 이로 인해 직접적인 구현(예: Fetch API 사용)보다 효율적이고 체계적인 데이터 관리가 가능함.
1. 자동 데이터 변환
- Axios는 서버에서 받은 데이터를 JSON 형태로 자동 변환하여 사용
- Axios 사용: 데이터를 바로 활용 가능.
axios.get('/api/data').then(response => { console.log(response.data); // 이미 JSON으로 변환된 데이터 }); - Fetch API 사용: 응답 데이터를 JSON으로 변환하는 추가 작업 필요.
fetch('/api/data') .then(response => response.json()) // 수동 변환 필요 .then(data => console.log(data));
- Axios 사용: 데이터를 바로 활용 가능.
2. 요청 및 응답 인터셉터 제공
- Axios는 인터셉터 기능을 통해 모든 요청과 응답을 일괄적으로 처리
- 예: 인증 토큰 추가, 공통 에러 처리 등.
-
// 요청 인터셉터: 모든 요청에 토큰 자동 추가 axios.interceptors.request.use(config => { config.headers.Authorization = 'Bearer token'; return config; }); // 응답 인터셉터: 공통 에러 처리 axios.interceptors.response.use(response => response, error => { console.error('Error occurred:', error); return Promise.reject(error); }); - Fetch를 사용할 경우 인터셉터 기능이 없어 매 요청마다 이런 작업을 반복적으로 구현해야 함
-
3. 에러 처리의 간소화
- Axios는 HTTP 상태 코드(4xx, 5xx)를 자동으로 에러로 감지하고 처리.
- Axios 사용:
axios.get('/api/data') .then(response => console.log(response.data)) .catch(error => console.error('Request failed:', error)); - Fetch 사용:
Fetch는 상태 코드가 4xx/5xx여도 응답을 성공으로 간주하므로 추가 확인이 필요.fetch('/api/data') .then(response => { if (!response.ok) { throw new Error('HTTP error! Status: ' + response.status); } return response.json(); }) .then(data => console.log(data)) .catch(error => console.error(error));
- Axios 사용:
4. 요청 취소 기능
- Axios는 요청을 취소할 수 있는 취소 토큰(Cancel Token)을 제공
- 예: 사용자가 입력하는 동안 중복된 요청을 방지.
const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/api/data', { cancelToken: source.token }) .catch(thrown => { if (axios.isCancel(thrown)) { console.log('Request canceled:', thrown.message); } }); // 요청 취소 source.cancel('Operation canceled by the user.'); - Fetch API는 기본적으로 요청 취소 기능을 지원하지 않아 별도의 라이브러리(예: AbortController)를 사용해야 합니다.
- 예: 사용자가 입력하는 동안 중복된 요청을 방지.
5. 요청 및 응답 설정의 유연성
- Axios는 기본값 설정과 재사용 가능한 요청 구성을 제공.
- 예: 모든 요청에 공통 헤더와 기본 URL을 추가.
const instance = axios.create({ baseURL: 'https://api.example.com', timeout: 5000, headers: { 'Authorization': 'Bearer token' } }); instance.get('/users'); // baseURL이 자동 적용됨 - Fetch를 사용할 경우, 매 요청마다 URL과 헤더를 반복적으로 설정해야 함.
- 예: 모든 요청에 공통 헤더와 기본 URL을 추가.
6. 데이터 전송 방식의 간소화
- Axios는 POST 요청의 본문 데이터를 JSON으로 변환하여 자동으로 전송.
- Axios 사용:
axios.post('/api/data', { name: 'John', age: 30 }); - Fetch 사용:
Fetch에서는 데이터를 JSON으로 변환하고 헤더를 수동으로 설정해야 함.fetch('/api/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'John', age: 30 }) });
- Axios 사용:
정리
- 간단한 요청이나 소규모 프로젝트에서는 Fetch API만으로 충분히 효율적으로 데이터를 관리할 수 있다.
- Fetch는 브라우저에 내장된 API로, 별도의 라이브러리 설치 없이도 동작한다.
- 그러나, 대규모 프로젝트나 복잡한 데이터 처리가 필요한 경우, Axios가 더 효율적이다.
- 요청 설정, 에러 처리, 인터셉터, 기본값 설정 등 Fetch로는 직접 구현해야 할 기능들을 Axios는 기본적으로 제공하므로 개발 시간을 절약하고 코드의 유지보수성을 높일 수 있다
'Computer Science > 네트워크' 카테고리의 다른 글
| 🌐 주소창에 URL을 입력했을 때 일어나는 과정! (1) | 2025.03.10 |
|---|---|
| 🔐JWT(JSON Web Token) 토큰에 대해 + vs 세션 기반 인증 (0) | 2025.02.02 |