Send AJAX Requests in Vue 2 with Axios, Fetch API

Last Updated on by in Vue JS
In this tutorial we learn how to make Ajax Fetch or GET requests in Vue js application using the Axios package and fetch API. AJAX requests helps in exchanging the data from the server, and update the page without the upload.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.

How Does AJAX Work?

Let us find out how does the Ajax work.

Handle AJAX Requests in Vue

  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.

Getting Started with Vue App

Install the latest Vue CLI on your 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

Node.js Gatsby error – “digital envelope routines::unsupported …”

Error: digital envelope routines::unsupported

opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'

To remove above error for invoking the app, make sure to update the "scripts": [] array in package.json file.

"scripts": {
    "serve": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service serve",
    "build": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build",
    "lint": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service lint"
},

Vue multi word error

To remove multi-word error warning, add the following code in vue.config.js file.

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
})

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.

Add code in App.vue file:

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

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

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

Further, we need to set up route, hence open the console, and run given command to install the vue router package.

npm add vue-router@^3.1.6

Now, you have to create the router/index.js file and below code in the given file.

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
  const routes = [
  {
    path: '/',
    name: 'ShowUsers',
    component: () => import('../components/ShowUsers.vue')
  }
]
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
export default router

Install Axios in Vue

Axios is an popular Promised based JavaScript library, here is the command to install Axios package in Vue.

npm install 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, It supports the Cross-Origin Resource Sharing (CORS).

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.

You have to add given code in the components/ShowUsers.vue file for displaying data, making fetch request.

<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>

Start the app in the browser.

npm run serve

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.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.