Axios는 HTTP 통신을 위한 라이브러리다. Vue 3 Composition API 기준으로 설정 방법을 정리했다.
Axios 설치
npm install axios
API 서비스 레이어 생성
컴포넌트마다 Axios를 import하는 대신, 재사용 가능한 인스턴스를 만든다.
// src/services/api.js
import axios from "axios";
const api = axios.create({
baseURL: "https://jsonplaceholder.typicode.com",
headers: {
"Content-Type": "application/json",
},
});
export default api;
컴포넌트에서 사용 (Composition API)
<template>
<div>
<button @click="fetchUsers">Load Users</button>
<div v-for="user in users" :key="user.id">
<h3></h3>
<p></p>
</div>
</div>
</template>
<script setup>
import { ref } from "vue";
import api from "@/services/api";
const users = ref([]);
async function fetchUsers() {
const { data } = await api.get("/users");
users.value = data;
}
</script>
Composable 패턴
fetch 로직을 composable로 분리하면 여러 컴포넌트에서 재사용할 수 있다.
// src/composables/useApi.js
import { ref } from "vue";
import api from "@/services/api";
export function useApi(url) {
const data = ref(null);
const error = ref(null);
const loading = ref(false);
async function fetch() {
loading.value = true;
try {
const res = await api.get(url);
data.value = res.data;
} catch (e) {
error.value = e;
} finally {
loading.value = false;
}
}
return { data, error, loading, fetch };
}
Interceptors
인증 토큰 주입이나 에러 핸들링에 interceptor를 쓰면 된다.
api.interceptors.request.use((config) => {
const token = localStorage.getItem("token");
if (token) config.headers.Authorization = `Bearer ${token}`;
return config;
});