Handling Ajax Request in Vue Applications Using Axios.
Tags: webdev, axios, vue, httprequest
Published: 2018-04-13 07:05:03

---
title: "Handling Ajax Request in Vue Applications Using Axios."
published: true
tags: web-development,axios,vuejs,http-request
canonical_url: 
---

![](https://cdn-images-1.medium.com/max/1024/1*miB-YGBcasaouoRP4rovng.jpeg)

Contemporarily, the prevalent Architecture for building web applications is a client-server model. This makes it very easy to build, especially, JavaScript Applications by fetching data from a remote source or consume an [API](https://en.wikipedia.org/wiki/Application_programming_interface). It can either be Publicly available APIs or the ones you personally built using frameworks like&nbsp;[Laravel](https://laravel.com/).

[Vue](https://vuejs.org/) offers the flexibility to build applications using data fetched from any API and conveniently serve content to the users of your applications.

For the purpose of this tutorial, we are going to explore one of the publicly available API [ICNDB](http://www.icndb.com/api/). Its basically a database of chuck norris jokes on the internet. Fetching data from this API will give us an overview of how to successfully communicate with information from a remote source using&nbsp;Axios.

A basic understanding of the concept of Vue will be a plus in order to be able to follow along properly in this tutorial.

### Making Ajax Request and Handling Responses

Handling Ajax request within a Vue application was previously made easy by using [vue-resource](https://github.com/pagekit/vue-resource), which has now been [retired](https://medium.com/the-vue-point/retiring-vue-resource-871a82880af4). This means any 3rd party libraries can be used for the purpose of making Ajax request, but as recommended by [Evan](https://twitter.com/youyuxi), we will use Axios. Axios is a commendable promise-based HTTP client library that runs on both the client and the&nbsp;server.

Now that we are conversant with the tools and what we intend to build, let’s get right into&nbsp;it.

### What we will&nbsp;Build

A sneak peek into what we will build in this tutorial.

![](https://cdn-images-1.medium.com/max/1024/1*6edx8b79WySFBSLdj3wUBQ.gif)<figcaption>What we will Build</figcaption>

Ready? Lets build&nbsp;it!

### Set Up Application

Vue CLI will be used here to quickly set up the application. This command line interface(Vue-CLI) provides a means of rapidly generating a Single Page Application in no time, we will install it in a bit. Before installing vue-cli globally on your system, I assume that you already have Node and npm installed, if otherwise quickly download them [here](https://nodejs.org/en/). Once you are done, you can verify Node and npm from the terminal with&nbsp;:

```
node -v

npm -v
```

Now install Vue-CLI&nbsp;:

```
npm install -g vue-cli
```

Having installed the CLI, vue command becomes available for scaffolding our application. Lets use it to create a project for this&nbsp;tutorial

```
vue init webpack-simple vue-axios
```

We used webpack-simple template instead of starting out with a blank&nbsp;page.

Next, change directory into the newly created project and install all the dependencies.

```
cd vue-axios

npm install
```

This might take few minutes to get all the necessary files installed, once the process is completed, start the application with&nbsp;:

```
npm run dev
```

This will start the application on your default browser on port 8080, as shown below&nbsp;:

![](https://cdn-images-1.medium.com/max/1024/1*fN6a_CpUh3ymfhFkryFcBw.png)

### Install Axios

One of the main objective of this tutorial is to learn how to seamlessly use axios in our application. Lets install it using npm&nbsp;:

```
npm install axios --save
```

Axios will be installed and save into the package.json file in our application.

Now that the necessary dependencies and tools have been installed. We will then build a component that will be used to make the API call described earlier and also render the fetched contents. Using Vue-CLI to scaffold an application will also generate a default component&nbsp;./src/App.vue Open this file and clear the contents in&nbsp;there

```
<template>

<div id="app">
...

</div>

</template>

<script>

export default {

name: 'app',

data () {

return {

}

}

}

</script>

<style>

</style>
```

This will result in an empty page if you check your browser now. Let the filling commence.

```
<template>
  <div id="app">
    <header>
      <span>Handling Ajax Request with Axios in Vue</span>
    </header>
    <main>
        <h2>Click the button to get Random jokes</h2>
        <button id="btn" class="" v-on:click="getJokes">Get Jokes</button>

        <div v-if="loading">
          <img src="../src/assets/loader.gif"/>
          Loading.....
        </div>

      <div class="wrapper">
        ... 
      </div>
    </main>
  </div>
</template>

<script>
...
</script>

<style>
...
</style>
```

So far, within this file, we have added a header in order to display the title of the application. And within the '\<main\>\</main\>' tag, we have a button that will call a function 'getJokes()’ once clicked. This function will be defined very&nbsp;soon.

Furthermore, we added a loader image that will be displayed once API call is initiated. This loader image will be hidden once our content has been received from the remote&nbsp;source.

Next we will set up the script to make the calls, loop through the data within our component in order to display the results and then add a little bit of&nbsp;styling.

Edit the 'App.vue' file&nbsp;:

```
<template>
...
</template>

<script>
  import axios from 'axios';
  
export default {
  name: 'app',
  data () {
    return {
      jokes: [],
      loading: false
    }
  }, 
  methods: {
    getJokes: function () {
      this.loading = true;
      axios.get("http://api.icndb.com/jokes/random/10")
      .then((response) => {
        this.loading = false;
        this.jokes = response.data.value;
      }, (error) => {
        this.loading = false;
      })
    }
  },
}
</script>

<style>
...
</style>
```

First of all, we imported axios into our component as we already have it installed. Then we setup the 'getJokes()' function and make API to '[http://api.icndb.com/jokes/random/10](http://api.icndb.com/jokes/random/10)', this will return 10 random jokes to be rendered. And lastly, we also set a condition for loading and hiding the image&nbsp;loader.

To view the content from our API calls, lets go back to the our component and set up the&nbsp;view:

```
<template>
  <div id="app">
        ...
        <div v-if="loading">
          ...
        </div>

      <div class="wrapper">
        <div class="row">
          <div v-for="joke in jokes" :key="joke.id">
          <div class="col-md-4 cards">
             <img src="https://placeimg.com/300/300/nature" class="img-responsive" alt="Random images placeholder"> 
            <div>
              <h3>{{ joke.id }}</h3>
              <p>{{ joke.joke }}</p>
              <p>{{ joke.category }}</p>
            </div>
          </div>
        </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
...
</script>

<style>
...
</style>
```

Here, we used the v-for directive to render a list of items based on the array fetched from the&nbsp;API.

In addition to the bootstrap framework used to style the application, we will also add a little bit of custom style&nbsp;:

```
<template>
  ...
</template>

<script>
   ...
</script>

<style>
  body {
  margin: 0;
}

#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
}

main {
  text-align: center;
  margin-top: 40px;
}

header {
  margin: 0;
  height: 56px;
  padding: 0 16px 0 24px;
  background-color: #35495E;
  color: #ffffff;
}

header span {
  display: block;
  position: relative;
  font-size: 20px;
  line-height: 1;
  letter-spacing: .02em;
  font-weight: 400;
  box-sizing: border-box;
  padding-top: 16px;
}

button {
  background: #51B767;
  color: #ffffff;
  padding: 15px;
  border-radius: 0;
  font-weight: bold;
  font-size: 15px;
  border: 0;
}

.cards {
  background: #F5F5F5;
  height:400px;
}
 .cards:hover {
  transform: translateY(-0.5em);
  background: #EBEBEB;
}

.cards {
   column-count: 1;
  column-gap: 1em;
    margin-top: 70px;

} 
</style>
```

Download the loader image loader.gif from&nbsp;[here](https://github.com/yemiwebby/vue-axios/blob/master/src/assets/loader.gif).

And refresh your browser&nbsp;:

![](https://cdn-images-1.medium.com/max/1024/1*Shgzy9U2qMR1heYg5uKbLA.gif)

And don’t forget to include the link tag for bootstrap in the application’s index.html file.

```
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
```

By now, your page should look properly&nbsp;aligned

![](https://cdn-images-1.medium.com/max/1024/1*xihoDGuq10sMcbwBtUKxYg.gif)

### Conclusion

In this post, we have only used Axios to make a GET request and obtain contents from an API. Axios is powerful enough to handle other HTTP request methods such as POST, PUT, PATCH and DELETE anywhere in our application. Feel free to improve on this and if you found this post useful, show some love with claps. The code can also be found [on&nbsp;github](https://github.com/yemiwebby/vue-axios).

* * *