How to use the Fetch API and Axios in your VueJS projects.

How to use the Fetch API and Axios in your VueJS projects.

  • 543

Requests in VueJS: Fetch API and Axios — A Comparison.How and when to use the Fetch API and Axios in your VueJS projects.

Before the Fetch API was released, Axios was the popular HTTP client for HTTP requests. However, now that the Fetch API is built into most modern browsers, we can use it to make HTTP requests much easier, which makes Axios kind of redundant in some cases.

In this article, we’ll go over the two ways, see how to use them, and try to come out with a verdict as to when and why each of them should be used.

As a side note, it should be mentioned that using libraries, like Axios, is not the only way to, essentially, speed up development. Another way would be to build your components as independent Lego blocks that you’d be able to reuse in and across other projects.

Fetch API

The Fetch API is a standard API for making HTTP requests on the browser.

It a great alternative to the old XMLHttpRequestconstructor for making requests.

It supports all kinds of requests, including GET, POST, PUT, PATCH, DELETE, and OPTIONS, which is what most people need.

To make a request with the Fetch API, we don’t have to do anything. All we have to do is to make the request directly with the fetchobject.

For instance, we can write:

App.vue

<template>
  <div id="app">
    {{data}}
  </div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      data: {}
    }
  },
  beforeMount(){
    this.getName();
  },
  methods: {
    async getName(){
      const res = await fetch('https://api.agify.io/?name=michael');
      const data = await res.json();
      this.data = data;
    }
  }
};
</script>

In the code above, we made a simple GET request from an API and then convert the data from JSON to a JavaScript object with the json() method.

Then we display the object’s data directly on the template.

We can also process response bodies in other formats with the Fetch API, including plain text and binary data.

Like most HTTP clients, we can send request headers and bodies with the Fetch API.

To send a request with HTTP headers, we can write:

App.vue

<template>
  <div id="app">
    <img :src="data.src.tiny">
  </div>
</template></span><span id="7b96" class="jt ix dr ar jq b fl jx jy jz ka kb jv r jw"><script>
export default {
  name: "App",
  data() {
    return {
      data: {
        src: {}
      }
    };
  },
  beforeMount() {
    this.getPhoto();
  },
  methods: {
    async getPhoto() {
      const headers = new Headers();
      headers.append(
        "Authorization",
        "api_key"
      );
      const request = new Request(
        "https://api.pexels.com/v1/curated?per_page=11&page=1",
        {
          method: "GET",
          headers,
          mode: "cors",
          cache: "default"
        }
      );</span> <span id="9115" class="jt ix dr ar jq b fl jx jy jz ka kb jv r jw">const res = await fetch(request);
      const { photos } = await res.json();
      this.data = photos[0];
    }
  }
};
</script>

In the code above, we used the Headers constructor, which is used to add requests headers to Fetch API requests.

The append method appends our 'Authorization' header to the request.

We’ve to set the mode to 'cors' for a cross-domain request and headers is set to the headers object returned by the Headersconstructor`.

The photo is then displayed on the template.

To make a request body, we can write the following:

<template>
  <div id="app">
    <form @submit.prevent="createPost">
      <input placeholder="name" v-model="post.name">
      <input placeholder="title" v-model="post.title">
      <br>
      <button type="submit">Create</button>
    </form>
    {{data}}
  </div>
</template></span><span id="3070" class="jt ix dr ar jq b fl jx jy jz ka kb jv r jw"><script>
export default {
  name: "App",
  data() {
    return {
      post: {},
      data: {}
    };
  },
  methods: {
    async createPost() {
      const request = new Request(
        "https://jsonplaceholder.typicode.com/posts",
        {
          method: "POST",
          mode: "cors",
          cache: "default",
          body: JSON.stringify(this.post)
        }
      );</span> <span id="6866" class="jt ix dr ar jq b fl jx jy jz ka kb jv r jw">const res = await fetch(request);
      const data = await res.json();
      this.data = data;
    }
  }
};
</script>

In the code above, we made the request by stringifying the this.post object and then sending it with a POST request.

Then we get the response the same way as we did before and display it.

As we can see, it’s not too hard to make requests with the Fetch API and it’s built into most browsers.

Axios

Axios is a popular HTTP client that works on both browser and Node.js apps.

We can install it by running:

npm i axios

Then we can use it to make requests a simple GET request as follows:

App.vue

<template>
  <div id="app">{{data}}</div>
</template></span><span id="ae51" class="jt ix dr ar jq b fl jx jy jz ka kb jv r jw"><script>
const axios = require("axios");</span><span id="5640" class="jt ix dr ar jq b fl jx jy jz ka kb jv r jw">export default {
  name: "App",
  data() {
    return {
      data: {}
    };
  },
  beforeMount(){
    this.getName();
  },
  methods: {
    async getName(){
      const { data } = await axios.get("https://api.agify.io/?name=michael");
      this.data = data;
    }
  }
};
</script>

In the code above, we call the axios.get method with the URL to make the request.

Then we assign the response data to an object.

If we want to make a request with headers, we can write:

App.vue

<template>
  <div id="app">
    <img :src="data.src.tiny">
  </div>
</template></span><span id="5443" class="jt ix dr ar jq b fl jx jy jz ka kb jv r jw"><script>
const axios = require("axios");</span><span id="332c" class="jt ix dr ar jq b fl jx jy jz ka kb jv r jw">export default {
  name: "App",
  data() {
    return {
      data: {}
    };
  },
  beforeMount() {
    this.getPhoto();
  },
  methods: {
    async getPhoto() {
      const {
        data: { photos }
      } = await axios({
        url: "https://api.pexels.com/v1/curated?per_page=11&page=1",
        headers: {
          Authorization: "api_key"
        }
      });
      this.data = photos[0];
    }
  }
};
</script>

In the code above, we made a GET request with our Pexels API key with the axios method, which can be used for making any kind of request.

If no request verb is specified, then it’ll be a GET request.

As we can see, the code is a bit shorter since we don’t have to create an object with the Headers constructor.

If we want to set the same header in multiple requests, we can use a request interceptor to set the header or other config for all requests.

For instance, we can rewrite the above example as follows:

main.js:

import Vue from "vue";
import App from "./App.vue";
const axios = require("axios");</span><span id="a871" class="jt ix dr ar jq b fl jx jy jz ka kb jv r jw">axios.interceptors.request.use(
  config => {
    return {
      ...config,
      headers: {
        Authorization: "api_key"
      }
    };
  },
  error => Promise.reject(error)
);</span><span id="ddea" class="jt ix dr ar jq b fl jx jy jz ka kb jv r jw">Vue.config.productionTip = false;</span><span id="5feb" class="jt ix dr ar jq b fl jx jy jz ka kb jv r jw">new Vue({
  render: h => h(App)
}).$mount("#app");

App.vue

<template>
  <div id="app">
    <img :src="data.src.tiny">
  </div>
</template></span><span id="dbfd" class="jt ix dr ar jq b fl jx jy jz ka kb jv r jw"><script>
const axios = require("axios");</span><span id="7816" class="jt ix dr ar jq b fl jx jy jz ka kb jv r jw">export default {
  name: "App",
  data() {
    return {
      data: {}
    };
  },
  beforeMount() {
    this.getPhoto();
  },
  methods: {
    async getPhoto() {
      const {
        data: { photos }
      } = await axios({
        url: "https://api.pexels.com/v1/curated?per_page=11&page=1"
      });
      this.data = photos[0];
    }
  }
};
</script>

We moved the header to main.js inside the code for our interceptor.

The first argument that’s passed into axios.interceptors.request.use is a function for modifying the request config for all requests.

And the 2nd argument is an error handler for handling error of all requests.

Likewise, we can configure interceptors for responses as well.

To make a POST request with a request body, we can use the axios.post method.

App.vue

<template>
  <div id="app">
    <form @submit.prevent="createPost">
      <input placeholder="name" v-model="post.name">
      <input placeholder="title" v-model="post.title">
      <br>
      <button type="submit">Create</button>
    </form>
    {{data}}
  </div>
</template></span><span id="6472" class="jt ix dr ar jq b fl jx jy jz ka kb jv r jw"><script>
const axios = require("axios");</span><span id="84dd" class="jt ix dr ar jq b fl jx jy jz ka kb jv r jw">export default {
  name: "App",
  data() {
    return {
      post: {},
      data: {}
    };
  },
  methods: {
    async createPost() {
      const { data } = await axios.post(
        "https://jsonplaceholder.typicode.com/posts",
        this.post
      );
      this.data = data;
    }
  }
};
</script>

We make the POST request with the axios.post method with the request body in the second argument.

Then we get back the response data by getting the data property from the resulting response.

Verdict

The Fetch API and Axios are similar in many ways. They’re both easily integrated into VueJS apps and they both, in essence, get the job done.

If you’re working on multiple requests, you’ll find that Fetch requires you to write more code than Axios, even when taking into consideration the setup needed for it. Therefore, for simple requests, Fetch API and Axios are quite the same. However, for more complex requests, Axios is better as it allows you to configure multiple requests in one place.