Handle AJAX Requests in Vue.js 2+ with Axios & fetch API

Last updated on by Digamber
This tutorial explains about making the Ajax Requests in Vue.js 2+ application using Axios and fetch API.

Vue.js is a lenient JavaScript framework for developing fast and user-friendly applications. Unluckily, Vue doesn’t have any suitable mechanism to make external HTTP calls. However, there are many ways through which we can handle HTTP requests.

In this tutorial, we are going to make Ajax Requests to consume third-party API using Axios http client and fetch API.

Let’s understand what Ajax is?

Ajax is an Asynchronous Javascript and XML, and It is a widely used technique to access the webserver from client-sde over HTTP and HTTPS protocol.

AJAX supports XMLHttpRequest (XHR) objects; We can use API to render the data from a remote server and update the specific part of a web page, and It doesn’t refresh the entire web page.

Advantages of Ajax

  • Quicker response time
  • Fast and user friendly
  • Self-governing server technology
  • AJAX communicates over HTTP Protocol
  • Supports Client-side template rendering
  • Can update a specific component of a web page

How Does AJAX Work?

Let us find out how does the Ajax work.

Handle AJAX Requests in Vue 2

  1. User makes a request via API from the client-side that directly goes to XMLHttpRequest object.
  2. HTTP Request is sent to the server by XMLHttpRequest object transfers the HTTP request to the webserver.
  3. The remote server communicates with the database using the preferred programming language.
  4. Data is fetched from the server.
  5. The server sends data in the form of XML or JSON to XMLHttpRequest.
  6. Shows data on the browser that is retrieved from a server using HTML and CSS.

Basic Ajax Request Example in JavaScript

Here is the basic Ajax request example coded in JavaScript for the GET method

// Make the HTTP request
var xhr = new XMLHttpRequest();
xhr.open('GET', 'manage-data.php');

// Track the state changes of the request.
xhr.onreadystatechange = function () {
	var DONE = 4;
	var OK = 200;
	if (xhr.readyState === DONE) {
		if (xhr.status === OK) {
			console.log(xhr.responseText); // 'Result'
		} else {
			console.log('Error: ' + xhr.status); // Request error.
		}
	}
};

// Send request
xhr.send(null);

Getting Started with Vue App

To install the Vue project, first, we need to install the latest Vue CLI 4 on our local development system.

npm install -g @vue/cli

Start installing a new Vue project.

vue create vue-ajax-requests

Get inside the project.

cd vue-ajax-requests

Start the app in the browser.

npm run serve

Create Vue Component

Create ShowUsers.vue file inside the components folder.

<template>
  <div>Vue Axios Http Client Example<div/>
</template>

<script>
export default {
  data() {
    return {};
  };
}
</script>

Import the Vue component inside the JavaScript script tag, define the component name inside the components:{ } object, and then define the component’s name within the template tag.

// App.vue

<template>
  <div id="app">
    <ShowUsers></ShowUsers>
  </div>
</template>

<script>
import ShowUsers from './components/ShowUsers.vue'

export default {
  name: 'App',
  components: {
    ShowUsers
  }
}
</script>

Install Axios in Vue

Axios is an extremely popular, Promised based JavaScript library for making HTTP requests. It is a Promise based HTTP client for the browser, and node.js it works smoothly on client and server.

  • Cancel requests
  • Supports the Promise API
  • Intercept request and response
  • Make http requests from node.js
  • Automatic transforms for JSON data
  • Transform request and response data
  • Make XMLHttpRequests from the browser
  • Client side support for protecting against XSRF

Use command to install Axios package in Vue.

# NPM
npm install axios --save


# Yarn
yarn add axios

Let’s see how to use axios in Vue component.

<script>
import axios from "axios";

export default {
  data() {
    return {};
  }
};
</script>

We are going to use following API from JSONPlaceholder. JSONPlaceholder is a simple fake REST API for testing and prototyping. It’s like an image placeholder but for web developers.

https://jsonplaceholder.typicode.com/users

We also have to define the mounted lifecycle hook in Vue to make the API calls.

<script>
import axios from "axios";

export default {
  data() {
    return {};
  },
  mounted() {
    axios.get("https://jsonplaceholder.typicode.com/users")
  }
};
</script>

Get and Display Data using Axios in Vue.js

In this step, we will make the Ajax Request using Axios and show you how to get a response from the server and handle it via Promise Object.

A promise object in JavaScript provides surety for a probable result in future. A promise has 3 presumable states: fulfilled, rejected, or pending.

<template>
  <div>
    <ul class="test-list" v-for="user in usersList" :key="user.id">
      <li class="test-list--item">
        <strong>{{ user.name }}</strong> <br>
        {{ user.email }} <br>
        {{ user.website }}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      usersList: []
    };
  },
  mounted() {
    axios.get("https://jsonplaceholder.typicode.com/users")
      .then(res => {
        this.usersList = res.data;
        console.log(this.usersList)
      })
      .catch(error => {
        console.log(error)
         // Manage errors if found any
      })
  }
};
</script>

<style>
ul {
  margin: 0 auto;
  width: 300px;
  text-align: left;  
}

li {
  display: block;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  padding: 15px;
}
</style>

The axios.get() method makes the API call and gets the response from the server. If the response is successful, then it goes to then block, and if it fails, then it goes to catch block.

Get and Display Data using Axios in Vue.js

Make AJAX Request in Vue.js with Fetch API

The Fetch API is a modernized substitute for XMLHttpRequest. Most of the libraries created considering XMLHttpRequest.

The Fetch API offers an uncomplicated interface for retrieving resources. You can quickly render the data from the server, and It supports the Cross-Origin Resource Sharing (CORS).

The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set.
MDN Doc

How to Make Request with Fetch?

Let’s check out a basic example of fetching a JSON file using fetch API:

fetch('https://api-url.json')
.then(function(response) {
  // Response comes here
})
.catch(function(error) {
  console.log('Found error: \n', error);
});

Pass the API URL in the fetch() method to get the response from the webserver. You can handle the server response in the then and catch block.

Here is the final code for displaying data, making fetch request.

// vue-template.vue

<template>
  <div>
    <ul class="test-list" v-for="user in usersList" :key="user.id">
      <li class="test-list--item">
        <strong>{{ user.name }}</strong> <br>
        {{ user.email }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      usersList: []
    };
  },
  mounted() {
    fetch("https://jsonplaceholder.typicode.com/users").then((res) => {
          return res.json();
      }).then((users) => {
          this.usersList.push(...users);
      }).catch(error => {
          console.log(error)
      }) 
  }
};
</script>

<style>
ul {
  margin: 0 auto;
  width: 300px;
  text-align: left;  
}

li {
  display: block;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  padding: 15px;
}
</style>

Conclusion

In this tutorial, we looked ad two separate ways to send Ajax requests from a Vue.js application. We learned how to make REST API calls to the server to get the data.