Axios는 HTTP 요청을 쉽게 보낼 수 있는 자바스크립트 라이브러리로, Vue.js 애플리케이션에서 자주 사용됩니다. 서버와 데이터를 주고받는 일이 많은 웹 애플리케이션에서 특히 유용합니다. 이제 Axios에 대해 자세히 설명해 드리겠습니다.
Axios는 npm 또는 yarn을 통해 설치할 수 있습니다.
npm install axios
설치 후, Vue.js 파일에서 Axios를 임포트하여 사용할 수 있습니다.
Axios는 REST API에 대한 GET, POST, PUT, DELETE 같은 HTTP 메서드를 쉽게 사용하게 해줍니다.
axios.get('<https://api.example.com/data>')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
axios.post('<https://api.example.com/data>', {
name: 'John',
age: 30
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
Axios는 다양한 HTTP 메서드를 지원하며, 각각의 메서드는 서버와 다른 방식으로 상호작용합니다.
Axios는 기본적으로 JSON 데이터를 요청 본문으로 전송하며, 객체 형식으로 데이터를 보낼 수 있습니다.
axios.post('/api/data', {
name: 'Alice',
email: 'alice@example.com'
});
Axios는 서버로부터 받은 응답 데이터를 자동으로 JSON으로 변환해줍니다. 응답 데이터는 response.data에 저장되며, 직접 접근할 수 있습니다.
axios.get('/api/data')
.then(response => {
console.log(response.data); // 응답 데이터 출력
});
Axios는 요청 시 매번 URL을 입력하지 않도록, 기본 URL을 설정할 수 있습니다.
const axiosInstance = axios.create({
baseURL: '<https://api.example.com>'
});
// 기본 URL이 적용된 GET 요청
axiosInstance.get('/data')
.then(response => {
console.log(response.data);
});
Axios는 HTTP 요청 시 헤더(Header)를 쉽게 설정할 수 있습니다. 예를 들어, 인증 토큰을 추가할 때 유용합니다.
axios.get('/api/data', {
headers: {
'Authorization': 'Bearer your_token'
}
})
.then(response => {
console.log(response.data);
});
GET 요청에 쿼리 파라미터를 쉽게 추가할 수 있습니다.
axios.get('/api/data', {
params: {
id: 123
}
})
.then(response => {
console.log(response.data);
});
Axios는 요청(Request) 또는 응답(Response)을 가로채서 추가 작업을 할 수 있는 인터셉터 기능을 제공합니다. 예를 들어, 요청 전에 인증 토큰을 추가하거나, 응답 에러를 일괄적으로 처리할 수 있습니다.
axios.interceptors.request.use(config => {
config.headers.Authorization = `Bearer ${token}`;
return config;
}, error => {
return Promise.reject(error);
});
axios.interceptors.response.use(response => {
return response;
}, error => {
// 오류 처리 로직
if (error.response.status === 401) {
console.error('Unauthorized access');
}
return Promise.reject(error);
});
요청 시간이 너무 오래 걸릴 경우 타임아웃을 설정하여 특정 시간 안에 응답이 오지 않으면 요청을 취소할 수 있습니다.
axios.get('/api/data', { timeout: 5000 })
.then(response => {
console.log(response.data);
})
.catch(error => {
if (error.code === 'ECONNABORTED') {
console.error('Request timed out');
} else {
console.error(error);
}
});
Axios는 요청을 취소할 수 있는 기능도 제공하며, 이를 통해 불필요한 요청을 취소하거나 중복 요청을 방지할 수 있습니다.
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/api/data', {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
})
})
.then(response => {
console.log(response.data);
})
.catch(error => {
if (axios.isCancel(error)) {
console.log('Request canceled');
} else {
console.error(error);
}
});
// 요청을 취소하려면 아래를 호출
cancel();
Vue.js 애플리케이션에서 Axios를 전역에서 사용할 수 있도록 설정할 수 있습니다. 이렇게 하면 모든 컴포넌트에서 this.$axios로 Axios를 사용할 수 있습니다.
import Vue from 'vue';
import axios from 'axios';
Vue.prototype.$axios = axios;
new Vue({
el: '#app',
render: h => h(App)
});
Vue 컴포넌트 내에서 Axios를 사용하여 API 요청을 보낼 수 있습니다. 예를 들어, mounted 훅에서 데이터를 불러올 수 있습니다.
export default {
data() {
return {
users: []
};
},
mounted() {
this.$axios.get('/api/users')
.then(response => {
this.users = response.data;
})
.catch(error => {
console.error(error);
});
}
};
Vuex를 사용해 상태 관리를 하는 경우, Axios를 액션 내에서 사용해 데이터를 가져올 수 있습니다.
export const actions = {
fetchData({ commit }) {
return axios.get('/api/data')
.then(response => {
commit('setData', response.data);
})
.catch(error => {
console.error(error);
});
}
};
Axios는 Vue.js 애플리케이션에서 서버와 데이터를 쉽게 주고받을 수 있게 해주는 강력한 HTTP 클라이언트입니다. 간단한 사용법과 다양한 기능을 제공하며, 인터셉터, 타임아웃 설정, 취소 토큰 등 고급 기능도 포함하고 있어 복잡한 요청 관리에도 적합합니다. Vue.js 프로젝트에서 서버와 상호작용할 때 매우 유용하게 사용할 수 있습니다.