Axios란?
- Axios는 HTTP 요청을 처리하는 JavaScript 라이브러리입니다.
- fetch API보다 사용이 간편하고 기능이 강력합니다.
- 주로 서버와 데이터를 주고받는 데 사용됩니다.
Axios 설치
npm install axios
1. GET 요청
import axios from "axios";
// GET 요청으로 데이터 가져오기
axios
.get("http://localhost:3000/posts")
.then(response => {
console.log("받은 데이터:", response.data); // response.data에 데이터가 있음
})
.catch(error => {
console.error("에러 발생:", error);
});
2. POST 요청
import axios from "axios";
// POST 요청으로 새로운 데이터 추가
axios
.post("http://localhost:3000/posts", {
title: "Axios Post",
content: "Axios is great!",
})
.then(response => {
console.log("추가된 데이터:", response.data); // 성공 시 반환된 데이터
})
.catch(error => {
console.error("에러 발생:", error);
});
1. DELETE, PATCH, fetch와의 비교
1) DELETE 요청
import axios from "axios";
// 특정 ID의 데이터를 삭제
axios
.delete("http://localhost:3000/posts/1")
.then(() => {
console.log("데이터 삭제 완료");
})
.catch(error => {
console.error("에러 발생:", error);
});
2)PATCH 요청
import axios from "axios";
// 특정 ID의 데이터를 일부 수정
axios
.patch("http://localhost:3000/posts/2", {
title: "Updated Title",
})
.then(response => {
console.log("수정된 데이터:", response.data);
})
.catch(error => {
console.error("에러 발생:", error);
});
2. Custom Instance, Interceptors
axios.create()로 기본 설정을 가진 Axios 인스턴스를 생성할 수 있습니다.
[예제]
import axios from "axios";
// Custom Axios Instance 생성
const api = axios.create({
baseURL: "http://localhost:3000", // 기본 URL 설정
timeout: 5000, // 요청 제한 시간 설정
headers: { "X-Custom-Header": "CustomValue" },
});
// GET 요청
api.get("/posts").then(response => console.log(response.data));
1) Interceptors
요청이나 응답을 가로채서 추가 처리를 할 수 있습니다.
[예제: 요청 인터셉터]
api.interceptors.request.use(
config => {
console.log("요청 전 처리:", config);
return config; // 요청을 진행
},
error => {
return Promise.reject(error); // 에러 처리
}
);
[예제: 응답 인터셉터]
api.interceptors.response.use(
response => {
console.log("응답 전 처리:", response);
return response; // 응답을 진행
},
error => {
console.error("응답 에러 처리:", error);
return Promise.reject(error);
}
);
'부캠 > REACT' 카테고리의 다른 글
[REACT] SUPABASE (1) | 2024.11.30 |
---|---|
[REACT] 스탠다스 심화주차 복습 (2) | 2024.11.25 |
[REACT] 심화주차 - JSON Server (1) | 2024.11.24 |
[REACT] 심화주차 - 비동기, 동기 (1) | 2024.11.24 |
[REACT] 강의 모르는 용어 (0) | 2024.11.23 |