How to Use Axios with Vue.js?

How to Use Axios with Vue.js

When building modern web applications with Vue.js, handling HTTP requests efficiently is crucial for fetching and sending data to servers. While Vue projects can use the native Fetch API, many Vue.js development company generally prefer using Axios, a powerful HTTP client. It simplifies API communication by offering features such as request interception, response transformation, automatic JSON parsing, and request cancellation. 

In this blog, we’ll explore how to use Axios with Vue.js. We’ll cover installation, how Axios works within a Vue.js application, sending and receiving data using GET and POST requests, setting up a common Axios instance, using interceptors to handle requests globally, managing asynchronous operations using async/await, error handling, and cancelling long-running requests.

1. What is Axios?

Axios is a JavaScript HTTP client library for making HTTP requests from Node.js or XMLHttpRequests from the browser. It is an open-source, promise-based library to make API calls. It runs on both client and server. Unlike the native Fetch API, Axios automatically transforms JSON data and doesn’t require manual parsing of responses. It’s commonly used in Vue.js applications, which do not include a built-in HTTP request helper. You can make requests using methods such as GET, POST, PUT/PATCH, and DELETE. 

Reddit discussion about Axios for a better understanding.

Reddit discussion about Axios

2. How Does Axios Work in Vue.js?

In Vue, Axios can be used either globally across the whole app or within individual components. It enables components to perform HTTP actions like GET, POST, PUT, and DELETE, making Axios a useful tool for interacting with RESTful APIs or accessing external data sources efficiently.

2.1 Prerequisites

Before you start, ensure that the system fulfills the following requirements:

  • A basic understanding of how Vue.js works
  • Node.js and npm are installed on your system.
  • Vue CLI is installed globally. Use the command below to install the Vue CLI if you haven’t. 
    npm install -g @vue/cli<br>

3. Setting Up Vue.js Project

Create a Vue project using Vue CLI:

vue create axios-demo

Once the project gets created, move into it using: 

cd axios-demo

3.1 Installation – Axios

We first need to install Axios, either using npm or yarn, to use it in our Vue.js application. Here, we’ll use npm to install Axios.

npm install axios

This adds Axios to your project’s dependencies, allowing you to import and use it in your Vue components.

3.2 Adding Axios to Your Vue.js Project

To make Axios available throughout your application, import it and register it globally in the main.js file.

// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import axios from 'axios';
 
const app = createApp(App);
 
// Attach axios to global properties
app.config.globalProperties.$axios = axios;
 
app.mount('#app');

Explanation:

  1. We import Vue’s createApp to start the application.
  2. Axios is also imported, so it can be added globally to the Vue instance.
  3. app.config.globalProperties.$axios = axios makes Axios available in any component as this.$axios.
  4. app.mount(‘#app’) mounts the application to the DOM element with id=”app”.

3.3 Populating Data with a GET Request

Axios can be used within your Vue components to retrieve data by calling it inside a method or lifecycle hook:

<template>
  <div>
    <h2>User List</h2>
    <ul v-if="users.length">
      <li v-for="user in users" :key="user.id">{{ user.name }}</li>
    </ul>
    <p v-else>Loading...</p>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      users: [],
    };
  },
  async created() {
    try {
      const response = await this.$axios.get('https://jsonplaceholder.typicode.com/users');
      this.users = response.data;
    } catch (error) {
      console.error("Error fetching users:", error);
    }
  },
};
</script>

Explanation:

  1. The data() function returns a user array that will contain the retrieved data.
  2. The created() lifecycle hook runs as soon as the component is created.
  3. A GET request to a placeholder API is sent using Axios. 
  4. response.data contains the user data and is assigned to the users array.
  5. In the template, if users contain data, it renders a list; otherwise, it shows “Loading…”.

3.4 Pushing Data with a POST Request

<template>
  <div>
    <input v-model="name" placeholder="Enter name" />
    <button @click="addUser">Add User</button>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      name: '',
    };
  },
  methods: {
    async addUser() {
      try {
        const response = await this.$axios.post('https://jsonplaceholder.typicode.com/users', {
          name: this.name,
        });
        console.log("User added:", response.data);
      } catch (error) {
        console.error("Error adding user:", error);
      }
    },
  },
};
</script>

Explanation:

  1. v-model binds the input field to the name in data.
  2. When the button is clicked, addUser() is called.
  3. Inside addUser, a POST request is sent to the API with the name as the payload.
  4. The response, which includes the new user data, is logged to the console.

3.5 Creating a Common Base Instance

A base instance is used to share a common base URL and configuration across multiple instances. This approach is useful when making multiple requests to the same server or when sharing headers. 

// src/axios.js
import axios from 'axios';
 
const instance = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com',
  headers: {
    'Content-Type': 'application/json',
  },
});
 
export default instance;

Explanation:

  1. We import Axios and call axios.create() to configure a base instance.
  2. The baseURL option sets the default root URL for all requests.
  3. Default headers ensure every request uses JSON.
  4. Exporting this instance allows reuse across components.

3.6 Using Interceptors in Axios

Axios provides the ability to run specific code before sending a request or after receiving a response by using request and response interceptors. These interceptors are useful for tasks such as setting headers (e.g., authorization or content type), handling request errors, managing loading states, or modifying response data. By using interceptors, developers can improve code structure and avoid repeating the same code across multiple components. 

To attach an interceptor to an Axios instance, you can use the interceptors property provided by Axios.

instance.interceptors.request.use(config => {
  console.log("Sending request to:", config.url);
  config.headers['Authorization'] = 'Bearer your_token_here';
  return config;
}, error => Promise.reject(error));
 
instance.interceptors.response.use(response => {
  return response;
}, error => {
  console.error("Error occurred:", error.response.status);
  return Promise.reject(error);
});

Explanation:

  • Request Interceptor:
    1. Intercepts each request before it’s sent.
    2. Logs the request URL.
    3. Adds an Authorization header.
  • Response Interceptor:
    1. Returns the response directly if there’s no error.
    2. Logs the status if an error occurs and propagates it.

3.7 Error Handling

To prevent your web app from crashing unexpectedly, handle errors properly by showing alerts or messages to inform the user. Instead of only logging errors to the console, catch them and display custom messages to improve the user experience. 

If the error object includes a response, inspect error.response to identify the issue. Likewise, if there’s a request field, error.request can help you diagnose what went wrong. Axios treats any HTTP response outside the 2xx range(for example, 401, 422, or 500) as an error and will trigger the catch block for handling.

try {
  const response = await axios.get('/data');
} catch (error) {
  if (error.response) {
    console.error("Server error:", error.response.status);
  } else if (error.request) {
    console.error("No response:", error.request);
  } else {
    console.error("Other error:", error.message);
  }
}

Explanation:

  1. error.response catches server errors (e.g., 500, 404).
  2. error.request handles cases when no response is received.
  3. The final block catches other errors, such as typos or setup issues.

3.8 Using Axios with Async/Await

We can write asynchronous code in Axios using async/await to handle HTTP requests.

async function fetchUsers() {
  try {
    const response = await axios.get('/users');
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

Explanation:

  1. async allows us to use await to pause execution until a request resolves.
  2. This avoids deeply nested .then() callbacks and keeps the code clean.

3.9 Cancelling Requests

Axios can cancel long-running requests if users leave the page before they finish. In such cases, the AbortController Web API allows cancelling the initiated request without waiting for a response once the user has left the page.

const controller = new AbortController();
 
axios.get('/users', { signal: controller.signal })
  .then(response => console.log(response.data))
  .catch(error => {
    if (axios.isCancel(error)) {
      console.log("Request canceled", error.message);
    } else {
      console.error("Error:", error);
    }
  });
 
// Cancel the request
controller.abort();

Explanation:

  1. Create an AbortController to control cancellation.
  2. Pass its signal to the request.
  3. If the controller is aborted, the request is canceled before it completes.
  4. This helps avoid unnecessary requests (e.g., when switching pages).

4. Final Thoughts

Axios is a robust and flexible library that makes handling HTTP requests in Vue.js applications easier. From fetching and submitting data to managing errors and customizing requests with interceptors, Axios simplifies communication with APIs. It supports both basic and advanced use cases, making it suitable for projects of any size.

FAQs

What is the difference between Axios and fetch in Vue?

In Axios, server responses are accessed through the response.data property, whereas with fetch(), the response body must be read explicitly and can then be stored in any variable. Both methods handle headers similarly when making requests.

Is Axios for Frontend or Backend?

Axios is primarily used on the frontend, but it can also be used on the backend.

Is Axios a RESTful API?

No, Axios is a JavaScript library that allows you to make HTTP requests such as GET, POST, PUT, and DELETE and interact with APIs, including RESTful API.

profile-image
Parind Shah

Parind Shah is responsible for frontend innovations at TatvaSoft. He brings profound domain experience and a strategic mindset to deliver exceptional user experience. He is always looking to gain and expand his skill set.

Comments

Leave a message...