Vue and Axios
Axios is a Promise-based HTTP client that can be used in browsers and Node.js. It is one of the most popular AJAX libraries in frontend development, favored for its powerful features and ease of use.
Why Choose Axios?
- Create XMLHttpRequests from browsers
- Create http requests from node.js
- Support Promise API
- Intercept requests and responses
- Transform request and response data
- Cancel requests
- Automatic JSON data conversion
- Client-side XSRF protection
Installing Axios
First, you need to add Axios to your project:
npm install axiosUsing Axios in Vue
You can import and use Axios directly in any component where you need to initiate HTTP requests.
GET Request Example
Let's rewrite the previous example of fetching an article list using Axios:
<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios' // Import axios
const posts = ref([])
const loading = ref(true)
const error = ref(null)
async function fetchData() {
loading.value = true
try {
// Use axios.get to initiate a request
const response = await axios.get('https://jsonplaceholder.typicode.com/posts')
// Axios places response data in response.data
posts.value = response.data
} catch (err) {
// Axios automatically handles non-2xx status codes and throws an error
error.value = err.message
} finally {
loading.value = false
}
}
onMounted(() => {
fetchData()
})
</script>
<template>
<!-- Template part is the same as the fetch example -->
<div>
<h1>Posts</h1>
<div v-if="loading">Loading...</div>
<div v-if="error" style="color: red;">{{ error }}</div>
<ul v-if="posts.length">
<li v-for="post in posts" :key="post.id">{{ post.title }}</li>
</ul>
</div>
</template>As you can see, the code is very similar to the fetch version but a bit more concise:
- No need to check
response.okbecause Axios automatically treats failed HTTP status codes as errors. - No need to manually call
.json()because Axios automatically parses JSON responses.
POST Request Example
Sending data to a server usually uses a POST request.
async function createPost() {
try {
const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1
});
console.log('Post created:', response.data);
} catch (error) {
console.error('Error creating post:', error);
}
}Creating an Axios Instance
In large applications, you might make many requests to the same API. To avoid repeating configurations (like base URL, timeout, request headers, etc.) in each request, you can create an Axios instance.
Typically, we create a dedicated file in the project to handle API-related configurations, such as src/api.js or src/utils/axios.js.
src/api.js
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://api.example.com',
headers: {
'Content-Type': 'application/json',
// You can add authentication tokens here
// 'Authorization': 'Bearer YOUR_TOKEN'
}
});
export default apiClient;Now, in your components, you can import and use this pre-configured instance:
MyComponent.vue
<script setup>
import apiClient from '../api.js'
async function fetchUsers() {
// The request will be sent to https://api.example.com/users
const response = await apiClient.get('/users')
// ...
}
</script>This approach greatly improves code maintainability and reusability.