Categories
Vue

Make HTTP Requests in a Vue App with Axios — Handling Errors and Cancellation

Spread the love

Axios is a popular HTTP client that is used with Vue apps.

In this article, we’ll look at how to make requests with Axios in a Vue app.

Removing Interceptors

We can remove request or response interceptors with the eject method.

For example, we can write:

<template>
  <div id="app"></div>
</template>
<script>
import axios from "axios";
const interceptor = axios.interceptors.response.use(
  config => {
    console.log(config);
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

export default {
  name: "App",
  async beforeMount() {
    const { data } = await axios({
      method: "get",
      url: "https://jsonplaceholder.typicode.com/posts/1"
    });
    console.log(data);
    axios.interceptors.request.eject(interceptor);
  }
};
</script>

to cal the eject method to remove the interceptor.

Add Interceptor to a Custom Instance of Axios

We can add a request or response interceptor to a custom instance of Axios.

To do that, we write:

<template>
  <div id="app"></div>
</template>
<script>
import axios from "axios";

const instance = axios.create({
  baseURL: "https://jsonplaceholder.typicode.com/posts",
  timeout: 1000,
  headers: { "X-Custom-Header": "foobar" }
});

instance.interceptors.response.use(
  config => {
    console.log(config);
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

export default {
  name: "App",
  async beforeMount() {
    const { data } = await instance.get("/1");
    console.log(data);
  }
};
</script>

We just call instance.interceptors.response.use to add the interceptor to the Axios instance.

We can replace response with request to add a request interceptor to an instance.

Handling Errors

To handle errors, we can catch them. For instance, we can write:

<template>
  <div id="app"></div>
</template>
<script>
import axios from "axios";

export default {
  name: "App",
  async beforeMount() {
    try {
      const { data } = await axios.get(
        "https://jsonplaceholder.typicode.com/posts/1"
      );
      console.log(data);
    } catch (error) {
      if (error.response) {
        console.log(error.response.data);
        console.log(error.response.status);
        console.log(error.response.headers);
      } else if (error.request) {
        console.log(error.request);
      } else {
        console.log("Error", error.message);
      }
      console.log(error.config);
    }
  }
};
</script>

We can check if the error is from the response or the request with the response and request properties.

The message property has the error message.

The config property has the config.

We can also validate the status with a function. Axios will only resolve if the status is what we want.

For example, we can write:

<template>
  <div id="app"></div>
</template>
<script>
import axios from "axios";

export default {
  name: "App",
  async beforeMount() {
    try {
      const { data } = await axios.get(
        "https://jsonplaceholder.typicode.com/posts/1",
        {
          validateStatus(status) {
            return status < 500;
          }
        }
      );
      console.log(data);
    } catch (error) {
      console.log(error);
    }
  }
};
</script>

to add the validateStatus method to resolve the promise returned by axios.get if the status code is less than 500.

Cancellation

To make a request cancellable, we can use a cancel token.

For example, we can write:

<template>
  <div id="app"></div>
</template>
<script>
import axios from "axios";
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

export default {
  name: "App",
  async beforeMount() {
    try {
      source.cancel("Operation canceled by the user.");
      const { data } = await axios.get(
        "https://jsonplaceholder.typicode.com/posts/1",
        {
          cancelToken: source.token
        }
      );
      console.log(data);
    } catch (thrown) {
      if (axios.isCancel(thrown)) {
        console.log("Request canceled", thrown.message);
      } else {
        // handle error
      }
    }
  }
};
</script>

We call the source.cancel method to cancel the request. The argument is the message to show.

axios.isCancel method lets us check if the request is canceled or not.

thrown.message has the message we passed into the argument.

Conclusion

We can handle errors and make requests cancellable with Axios.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *