Introduction

In Vue 2.0, the developers decided that having a built-in HTTP client module was rather redundant and could be better serviced by third-party libraries. The alternative most frequently recommended is Axios.
Axios is an HTTP client library. It uses promises by default and runs on both the client and the server, which makes it appropriate for fetching data during server-side rendering. Because it uses promises, you can combine it with async/await to get a concise and easy-to-use API.
In this article, you’ll explore adding Axios to a Vue.js project for tasks involving populating data and pushing data. You will also learn about creating a reusable base instance.

Prerequisites

To follow along with this article, you will need:

Node.js installed locally, which you can do by following How to Install Node.js and Create a Local Development Environment.

Installing and Importing axios

To begin, you must install Axios.
You can install Axios with npm:

npm install axios --save

Or with Yarn:

yarn add axios

When adding Axios to your Vue.js project, you will want to import it:

import axios from 'axios';

Next, we will use axios.get() to make a GET request.

Populating Data with a GET Request

You can use Axios directly in your components to fetch data from a method or lifecycle hook:
ExampleComponentGet.vue

<template>
  <div>
    <ul v-if="posts && posts.length">
      <li v-for="post of posts">
        <p><strong>{{post.title}}</strong></p>
        <p>{{post.body}}</p>
      </li>
    </ul>

    <ul v-if="errors && errors.length">
      <li v-for="error of errors">
        {{error.message}}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      posts: [],
      errors: []
    }
  },

  // Fetches posts when the component is created.
  created() {
    axios.get(`http://jsonplaceholder.typicode.com/posts`)
    .then(response => {
      // JSON responses are automatically parsed.
      this.posts = response.data
    })
    .catch(e => {
      this.errors.push(e)
    })
  }
}
</script>

The async/await version would look like this:
ExampleComponentGet.vue

<!-- ... template code ... -->

<script>
import axios from 'axios';

export default {
  data() {
    return {
      posts: [],
      errors: []
    }
  },

  // Fetches posts when the component is created.
  async created() {
    try {
      const response = await axios.get(`http://jsonplaceholder.typicode.com/posts`)
      this.posts = response.data
    } catch (e) {
      this.errors.push(e)
    }
  }
}
</script>

This code will retrieve "posts" from JSONPlaceholder and populate an unordered list with the "posts". Any "errors" encountered will appear in a separate unordered list.
Next, we will use axios.post() to make a POST request.

Pushing Data with a POST Request

You can use Axios to send POST, PUT, PATCH, and DELETE requests.

Note: You will not want to send requests on every input event. Consider using throttling or debouncing.

ExampleComponentPost.vue

<template>
  <div>
    <input type="text" v-model="postBody" @change="postPost()" />
    <ul v-if="errors && errors.length">
      <li v-for="error of errors">
        {{error.message}}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      postBody: '',
      errors: []
    }
  },

  methods: {
    // Pushes posts to the server when called.
    postPost() {
      axios.post(`http://jsonplaceholder.typicode.com/posts`, {
        body: this.postBody
      })
      .then(response => {})
      .catch(e => {
        this.errors.push(e)
      })
    }
  }
}
</script>

The async/await version would look like this:
ExampleComponentPost.vue

<!-- ... template code ... -->

<script>
import axios from 'axios';

export default {
  data() {
    return {
      postBody: '',
      errors: []
    }
  },

  methods: {
    // Pushes posts to the server when called.
    async postPost() {
      try {
        await axios.post(`http://jsonplaceholder.typicode.com/posts`, {
          body: this.postBody
        })
      } catch (e) {
        this.errors.push(e)
      }
    }
  }
}
</script>

This code creates an input field that will submit content to JSONPlaceholder. Any errors encountered will appear in an unordered list.
Next, we will use axios.create() to make a base instance.

Creating a Common Base Instance

A frequently overlooked but very useful capability Axios provides is the ability to create a base instance that allows you to share a common base URL and configuration across all calls to the instance. This comes in handy if all of your calls are to a particular server or need to share headers, such as an Authorization header:
http-common.js

import axios from 'axios';

export const HTTP = axios.create({
  baseURL: `http://jsonplaceholder.typicode.com/`,
  headers: {
    Authorization: 'Bearer {token}'
  }
})

You can now use HTTP in your component:
ExampleComponentBase.vue

<template>
  <div>
    <ul v-if="posts && posts.length">
      <li v-for="post of posts">
        <p><strong>{{post.title}}</strong></p>
        <p>{{post.body}}</p>
      </li>
    </ul>

    <ul v-if="errors && errors.length">
      <li v-for="error of errors">
        {{error.message}}
      </li>
    </ul>
  </div>
</template>

<script>
import { HTTP } from './http-common';

export default {
  data() {
    return {
      posts: [],
      errors: []
    }
  },

  created() {
    HTTP.get(`posts`)
    .then(response => {
      this.posts = response.data
    })
    .catch(e => {
      this.errors.push(e)
    })
  }
}
</script>

This code uses the configuration established in http-common.js and connects to JSONPlaceholder with the Authorization header. It retrieves the posts and catches any errors.

Conclusion

In this article, you were introduced to using Axios for populating data and pushing data. And also how to create a reusable base instance. That’s just scratching the surface of what Axios can do.
Visit the GitHub repository for more information and documentation on Axios.
If you’d like to learn more about Vue.js, check out our Vue.js topic page for exercises and programming projects.