0
0
Vueframework~5 mins

Axios setup and configuration in Vue

Choose your learning style9 modes available
Introduction

Axios helps you talk to servers easily from your Vue app. Setting it up right makes your app get data smoothly.

You want to get data from a website or API in your Vue app.
You need to send information like forms or login details to a server.
You want to handle errors or loading states when fetching data.
You want to set a base URL so you don't repeat it in every request.
You want to add headers like tokens for secure requests.
Syntax
Vue
import axios from 'axios';

const apiClient = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 10000,
  headers: { 'Content-Type': 'application/json' }
});

Use axios.create() to make a custom instance with your settings.

Set baseURL to avoid typing full URLs every time.

Examples
This sets a base URL for all requests made with api.
Vue
import axios from 'axios';

// Basic setup with base URL
const api = axios.create({
  baseURL: 'https://api.example.com'
});
Adds a timeout so requests stop if they take longer than 5 seconds.
Vue
const api = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 5000
});
Sets a header for all requests, useful for login tokens.
Vue
const api = axios.create({
  headers: { 'Authorization': 'Bearer mytoken123' }
});
Sample Program

This Vue component uses Axios to get posts from a public API when it loads. It shows loading text, errors, or the list of posts.

Vue
<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

const apiClient = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com',
  timeout: 8000,
  headers: { 'Content-Type': 'application/json' }
});

const posts = ref([]);
const error = ref(null);
const loading = ref(true);

onMounted(async () => {
  try {
    const response = await apiClient.get('/posts');
    posts.value = response.data;
  } catch (err) {
    error.value = 'Failed to load posts';
  } finally {
    loading.value = false;
  }
});
</script>

<template>
  <main>
    <h1>Posts</h1>
    <p v-if="loading">Loading posts...</p>
    <p v-if="error" role="alert" style="color: red">{{ error }}</p>
    <ul v-if="!loading && !error">
      <li v-for="post in posts" :key="post.id">
        <strong>{{ post.title }}</strong><br />
        {{ post.body }}
      </li>
    </ul>
  </main>
</template>
OutputSuccess
Important Notes

Always handle errors to avoid your app crashing if the server is down.

Use timeout to stop waiting too long for a response.

Set headers like Authorization for secure APIs.

Summary

Axios setup uses axios.create() to make a reusable client.

Set baseURL, timeout, and headers to customize requests.

Use the client in Vue lifecycle hooks to fetch data and update the UI.