Vue.js
Beginner
1 min read
Using Axios in Vue 3
Example
// src/lib/axios.ts
import axios from 'axios';
import { useAuthStore } from '@/stores/auth';
const api = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL ?? 'https://api.example.com',
timeout: 10_000,
headers: { 'Content-Type': 'application/json' },
});
// Attach token on every request
api.interceptors.request.use((config) => {
const auth = useAuthStore();
if (auth.token) config.headers.Authorization = `Bearer ${auth.token}`;
return config;
});
// Global error handler
api.interceptors.response.use(
(res) => res,
(err) => {
if (err.response?.status === 401) {
const auth = useAuthStore();
auth.logout();
}
return Promise.reject(err);
}
);
export default api;
// ── Component using the shared instance ───────
<script setup>
import { ref, onMounted } from 'vue';
import api from '@/lib/axios';
const post = ref(null);
const isLoading = ref(false);
onMounted(async () => {
isLoading.value = true;
const { data } = await api.get('/posts/1');
post.value = data;
isLoading.value = false;
});
</script>