Telerik blogs

In this article, we will look at how to use the Axios HTTP client with Vue.js to make HTTP requests in our Vue apps.

Axios is a popular JavaScript HTTP client library that is used on frontend apps. It has an easy-to-use API that lets us make all types of HTTP requests. In our Vue apps, we often need to make requests to external APIs via HTTP to send and receive data.

In this article, we will look at how to use the Axios client with Vue.js to make HTTP requests in our Vue apps.

Library Installation

We can install the Axios library easily.

To install it, we run:

npm i axios

with npm.

We can also install the library with Yarn by running:

yarn add axios

Make Basic GET Request

To make basic HTTP requests in our Vue app, we can import the library directly.

For instance, to make a GET request in our component, we write:

<template>
  <div>{{ answer }}</div>
</template>

<script>
import axios from "axios";

export default {
  name: "App",
  data() {
    return {
      answer: {},
    };
  },
  methods: {
    async getAnswer() {
      const { data } = await axios.get("https://yesno.wtf/api");
      this.answer = data;
    },
  },
  beforeMount() {
    this.getAnswer();
  },
};
</script>

to define the getAnswer method that calls axios.get to make a GET request to https://yesno.wtf/api.

It returns a promise with the response data with the data property having the response body. Then we assign that to the this.answer reactive property so we can display the response body in the template.

We call this.getAnswer in the beforeMount hook so that this method is called immediately before the component is being mounted.

As a result, we should get a response like:

{
  "answer": "no",
  "forced": false,
  "image": "https://yesno.wtf/assets/no/6-4bf0a784c173f70a0cab96efd9ff80c9.gif"
}

Make More Complex GET Requests

Axios can let us make more complex requests. For instance, we can make a GET request with a query with the params option.

For instance, we write:

<template>
  <div>{{ answer }}</div>
</template>

<script>
import axios from "axios";

export default {
  name: "App",
  data() {
    return {
      answer: {},
    };
  },
  methods: {
    async getBitcoinIndex() {
      const { data } = await axios.get(
        "https://api.coindesk.com/v1/bpi/historical/close.json",
        {
          params: {
            start: "2022-09-01",
            end: "2022-09-05",
          },
        }
      );
      this.answer = data;
    },
  },
  beforeMount() {
    this.getBitcoinIndex();
  },
};
</script>

We put the request query parameters in the object we set as the value of the params property in the object we pass in as the second argument.

We add the start and end query parameters which are set to date strings. They will both be included in the query string after the URL in the first argument since they are not undefined.

Therefore, Axios should make a GET request to https://api.coindesk.com/v1/bpi/historical/close.json?start=2022-09-01&end=2022-09-05 to get the response data.

We can catch any errors that are raised when making requests with Axios. To do this, we just wrap our Axios calls with a try-catch block.

For instance, we write:

<template>
  <div>{{ answer }}</div>
</template>

<script>
import axios from "axios";

export default {
  name: "App",
  data() {
    return {
      answer: {},
    };
  },
  methods: {
    async getBitcoinIndex() {
      try {
        const { data } = await axios.get(
          "https://api.coindesk.com/v1/bpi/historical/close.json",
          {
            params: {
              start: "2029-09-01",
              end: "2029-09-05",
            },
          }
        );
        this.answer = data;
      } catch (error) {
        console.log(error);
      }
    },
  },
  beforeMount() {
    this.getBitcoinIndex();
  },
};
</script>

to wrap the axios.get call with a try block so that any errors raised by Axios will be caught with the catch block.

This request will trigger a 404 response to be returned if the date range is in the future, so we can see the error object logged in the catch block if this request is made before the date range.

Make Requests That Sends a JSON Request Body

To make requests that send a JSON body, we can pass in the data as the second argument of the Axios request method.

For instance, we write:

<template>
  <div>{{ post }}</div>
</template>

<script>
import axios from "axios";

export default {
  name: "App",
  data() {
    return {
      post: {},
    };
  },
  methods: {
    async createPost() {
      try {
        const { data } = await axios.post(
          "https://jsonplaceholder.typicode.com/posts",
          {
            title: "foo",
            body: "bar",
            userId: 1,
          }
        );
        this.post = data;
      } catch (error) {
        console.log(error);
      }
    },
  },
  beforeMount() {
    this.createPost();
  },
};
</script>

to define the createPost method.

In it, we call axios.post to make a POST request with the POST request URL. The second argument is an object with the JSON request body.

It also returns a promise with the response in the same format as axios.get, so we get the response body with data.

We can make PATCH and PUT requests the same way by calling axios.patch and axios.put respectively.

Send Requests with a Multipart/Form-Data Format Request Body

To make requests with a multipart/form-data format request body, we can use the FormData constructor.

For instance, we write:

<template>
  <div>{{ response }}</div>
</template>

<script>
import axios from "axios";

export default {
  name: "App",
  data() {
    return {
      response: {},
    };
  },
  methods: {
    async createPost() {
      const formData = new FormData();
      formData.append("foo", "bar");
      const { data } = await axios.post("https://httpbin.org/post", formData);
      this.response = data;
    },
  },
  beforeMount() {
    this.createPost();
  },
};
</script>

to call axios.post with a FormData object.

We create a FormData object with the FormData constructor. And we call append with the key and value we want to send respectively.

Send Requests with Headers

We can send requests with request headers with Axios.

For instance, we write:

<template>
  <div>{{ answer }}</div>
</template>

<script>
import axios from "axios";

export default {
  name: "App",
  data() {
    return {
      answer: {},
    };
  },
  methods: {
    async getAnswer() {
      const { data } = await axios.get("https://yesno.wtf/api", {
        headers: {
          "content-type": "text/json",
        },
      });
      this.answer = data;
    },
  },
  beforeMount() {
    this.getAnswer();
  },
};
</script>

to make a GET request with axios.get with an object with the headers property as the second argument, which is set to an object with the request header key-value pairs.

To do the same with POST, PUT and PATCH requests, we write:

<template>
  <div>{{ post }}</div>
</template>

<script>
import axios from "axios";

export default {
  name: "App",
  data() {
    return {
      post: {},
    };
  },
  methods: {
    async createPost() {
      try {
        const { data } = await axios.post(
          "https://jsonplaceholder.typicode.com/posts",
          {
            title: "foo",
            body: "bar",
            userId: 1,
          },
          {
            headers: {
              "content-type": "text/json",
            },
          }
        );
        this.post = data;
      } catch (error) {
        console.log(error);
      }
    },
  },
  beforeMount() {
    this.createPost();
  },
};
</script>

to make a POST request with the same headers.

This time we put the headers in the object we use as the third argument of axios.post.

We do the same with axios.put and axios.patch for PUT and PATCH requests respectively.

Request Interceptors

In Vue apps, we tend to make several requests, and we often are doing the same thing in many requests.

To make this easy, Axios provides us with the request and response interceptors feature.

To add them, we write:

<template>
  <div>{{ answer }}</div>
</template>

<script>
import axios from "axios";

axios.interceptors.request.use(
  (config) => {
    config.headers = {
      ...config.headers,
      "content-type": "text/json",
    };
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  (response) => {
    console.log(response);
    response.data.foo = "bar";
    return response;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default {
  name: "App",
  data() {
    return {
      answer: {},
    };
  },
  methods: {
    async getAnswer() {
      const { data } = await axios.get("https://yesno.wtf/api");
      this.answer = data;
    },
  },
  beforeMount() {
    this.getAnswer();
  },
};
</script>

to call axios.interceptors.request.use to add a request interceptor.

The first argument is a function that lets us change the request config before any request is made.

In our example, we added the content-type request header to each request and set it to 'text/json'. Therefore, all requests we made will include the content-type request header and its value set to 'text/json'.

The second argument is a function that’s called when there’s any errors with making the request. We return a rejected promise with the error as the reason so the rejection will be surfaced.

Likewise, we add a response interceptor with axios.interceptors.response.use.

The function used as the first argument is the response handler function. It is called when a response is received.

In it, we add a foo property to all responses and set its value to 'bar' by setting response.data.foo to 'bar'. As a result, the response displayed on the template will have the foo property set to 'bar'.

And the second argument is a function that is called when an error response is received. Like the request error handler, we return a rejected promise with the error as the reason, so the rejection will be surfaced when there’s an error response.

Conclusion

We can make many kinds of requests easily with various options with the Axios API. And we can add request and response interceptors to modify and handle requests and responses globally in our Vue app. So Axios and Vue.js work together very well.


Vue
About the Author

John Au-Yeung

John Au-Yeung is a frontend developer with 6+ years of experience. He is an avid blogger (visit his site at https://thewebdev.info/) and the author of Vue.js 3 By Example.

Related Posts

Comments

Comments are disabled in preview mode.