Vue JS Make HTTP Requests with Axios and Fetch Tutorial

Throughout this significant guide, you will understand the process of making HTTP requests in Vue JS, to make the http request in vue, we will use Axios and JavaScript fetch API.

HTTP stands for Hypertext Transfer Protocol, and it offers an eloquent way to establish agile communication between client and server. Specific data is sent to the server from the client side; this process is known as an HTTP request. You will learn to make HTTP requests using the REST API from the Vue ecosystem; we will undoubtedly use the Axios and Fetch API to process the HTTP requests in the vue application.

Axios is helpful in-app development proliferation; it is an intuitive promise-based HTTP client, ideally associated with the XMLHttpRequests service.

The Fetch API is pragmatic in nature and gives you access to mold parts of the HTTP requests and responses. Additionally, fetch handles the HTTP-related notions such as CORS and extensions to HTTP.

  • Step 1: Set Up Vue CLI
  • Step 1: Create Vue Project
  • Step 1: Add Axios in Vue
  • Step 2: Create Components in Vue
  • Step 3: Create Fake API with JSON Server
  • Step 4: Vue Axios HTTP GET
  • Step 5: Vue Fetch HTTP GET
  • Step 6: Run Vue App

Set Up Vue CLI

Making HTTP GET request vue is a secondary thing; the first and foremost task is to install Vue CLI on your device.

npm install -g @vue/cli

Create Vue Project

Vue CLI makes the vue app installation exorbitantly easy, shake a leg and hit the provided command.

vue create vue-astro-app

cd vue-astro-app

Add Axios in Vue

Proliferate the HTTP requests reach in vue by installing the Axios package into the vue app.

npm install axios

Create Components in Vue

Next, create HttpAxios.vue template file within the components directory.

<template>
  
</template>

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

Further, create HttpFetch.vue template file inside the components folder.

<template>
  
</template>

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

Plus, trigger the vue components by adding them into the src/App.vue file.

<template>
  <div class="container mt-4">
    <HttpAxios />
    <HttpFetch />
  </div>
</template>

<script>
  import HttpAxios from './components/HttpAxios'
  import HttpFetch from './components/HttpFetch'

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

<style scoped>
   .container {
      max-width: 500px;
   }
</style>

Create Fake API with JSON Server

Next, following command can be invoked for installing json-server library in vue app.

npm install json-server

JSON server requires a specific configuration, thus create backend/db.json file, after that place the following code into the file.

{
  "posts": [
    {
      "id": 1,
      "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
      "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
    },
    {
      "id": 2,
      "title": "qui est esse",
      "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
    },
    {
      "id": 3,
      "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
      "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
    },
    {
      "id": 4,
      "title": "eum et est occaecati",
      "body": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
    },
    {
      "id": 5,
      "title": "nesciunt quas odio",
      "body": "repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest aut tenetur dolor neque"
    }
  ]
}

Further, start the json backend with suggested command.

json-server --watch backend/db.json --port 5555

Vue Axios HTTP GET Request

Time has come to show you how to make HTTP GET request using REST API in vue, lay down the entire code in src/components/HttpAxios.vue file.

<template>
  <div>
    <ul class="list-group" v-for="post in BLOG" :key="post.id">
      <li class="list-group-item list-group-item-action mb-3">
        <h3>{{ post.title }}</h3>
        {{ post.body }}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      BLOG: []
    };
  },
  mounted() {
    axios.get("http://localhost:5555/posts")
      .then(response => {
        this.BLOG = response.data;
        console.log(this.BLOG)
      })
      .catch(error => {
        alert(error)
      })
  }
};
</script>

Here are the available methods that amplify the HTTP request-making process with Axios.

axios#request(config)

axios#get(url[, config])

axios#delete(url[, config])

axios#head(url[, config])

axios#options(url[, config])

axios#post(url[, data[, config]])

axios#put(url[, data[, config]])

axios#patch(url[, data[, config]])

axios#getUri([config])

Vue Fetch HTTP GET Request

Let us use another method to deal with the server communication process. Use the JavaScript Fetch API to fetch the data from the JSON server swiftly.

Update code in src/components/HttpFetch.vue file.

<template>
  <div>
    <ul class="list-group" v-for="post in BLOG" :key="post.id">
      <li class="list-group-item list-group-item-action mb-3">
        <h3>{{ post.title }}</h3>
        {{ post.body }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      BLOG: []
    };
  },
  mounted() {
    fetch("http://localhost:5555/posts")
      .then(response => {
        this.BLOG = response.data;
        console.log(this.BLOG)
      })
      .catch(error => {
        alert(error)
      })
  }
};
</script>

Run Vue App

npm run serve
http://localhost:8080

Vue JS Axios HTTP

Conclusion

We have described how to use Axios and fetch in vue to make the HTTP requests profoundly. However, we would like to address some of the benefits of Axios that you may find better than Fetch API.
Axios is excellent at supporting older browsers; with Axios, you can cancel a request, you are allowed to define a response timeout, it comes with profound CSRF protection, not just that but also you can track upload progress.

Generically, we also told you how to create a demo REST API using JSON-server library, and we assume you have liked this guide. Thank you, have a good day.