Axios는 Promise API를 활용하는 HTTP 비동기 통신 라이브러리
npm install axios
axios(config)
axios를 이용해 HTTP 요청을 보낼 때, 요청에 대한 설정을 config에 담아야 함
| config | description |
|---|---|
| url | 요청을 보낼 서버 URL |
| method | HTTP 요청 메서드 |
| baseURL | 공통적으로 사용하는 기본 URL 주소 |
| headers | 사용자 지정 헤더 |
| params | URL의 쿼리 매개변수 |
| data | 요청 body로 보낼 데이터 |
| timeout | 요청 응답 중단 시간 |
| withCredentials | 쿠키 및 HTTP 인증 정보를 포함하도록 설정하는 옵션 |
| auth | 요청에 대한 HTTP 기본 인증 |
| responseTYpe | 서버에서 받을 응답의 데이터 타입 |
axios.create 를 이용하여 axios instance 생성
const instance: Axios = axios.create({
baseURL: "http://localhost:5175",
timeout: 40000,
headers: {
'Content-Type': 'application/json',
},
withCredentials: true,
});
then 또는 catch로 처리되기 전에 요청과 응답을 가로챌 수 있음
// 요청 인터셉터
axios.interceptors.request.use(function (config) {
return config;
}, function (error) {
return Promise.reject(error);
});
// 응답 인터셉터
axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
return Promise.reject(error);
});
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.post(url[, data, config])
axios.patch(url[, data, config])
axios.put(url[, data, config])
axios.head(url[, config])
axios.options(url[, config])
GET 방식은 서버에서 데이터를 받아서 보여줄 때 사용
const getLists = async () => {
axios.get("요청할 주소")
.then(res => {
console.log(res.data)
}).catch(err => {
console.log(err);
})
}
POST 메소드의 두 번째 인자는 요청주소로 보낼 데이터 객체
const postList = async () => {
const { data } = await axios.post(
"요청할 주소",
"보낼 값(객체)",
{
headers: {
'Content-type': 'application/json',
'Accept': 'application/json'
}
}).then(res => {
console.log(res.data);
}).catch(err => {
console.log(err)
})
}
DELETE 메소드는 데이터베이스의 내용을 삭제할 떄 사용
const deleteList = async (listId) => {
const { data } = await axios.delete(`요청할 주소/${listId}`)
}