Effortlessly Make Async HTTP Requests with Axios

Effortlessly Make Async HTTP Requests with Axios

Effortlessly Make Async HTTP Requests with Axios was initially published on Wednesday January 04 2023 on the Tech Dev Blog. For the latest up-to-date content, fresh out of the oven, visit https://techdevblog.io and subscribe to our newsletter!

Axios is a popular JavaScript library for making HTTP requests. It is promise-based, and makes it easy to work with asynchronous requests in your applications. In this tutorial, we will go over some of the best practices for using Axios to make HTTP requests.

Installing Axios

To use Axios in your project, you will first need to install it. You can do this using either npm or yarn.

npm

To install Axios using npm, run the following command in your terminal:

npm install axios

yarn

To install Axios using yarn, run the following command in your terminal:

yarn add axios

Making Requests

Once you have Axios installed, you can start making HTTP requests. Here is an example of a simple GET request:

axios.get('/api/users')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

In this example, we are making a GET request to the /api/users endpoint. If the request is successful, the response data will be logged to the console. If there is an error, it will be caught and logged to the console.

You can also make POST requests using Axios. Here is an example of a POST request:

axios.post('/api/users', {
  name: 'John Smith',
  email: 'john@example.com'
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

In this example, we are making a POST request to the /api/users endpoint with a payload containing a name and email.

Customizing Requests

You can customize your Axios requests by passing in additional options as an object. For example, you can pass in headers, params, and other options.

axios.get('/api/users', {
  headers: {
    'Authorization': 'Bearer abc123'
  },
  params: {
    page: 2
  }
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

In this example, we are passing in an Authorization header with a bearer token, and a page param with a value of 2.

Working with Promises

Axios uses Promises to handle asynchronous requests. This means that you can use the then and catch methods to handle success and error cases.

axios.get('/api/users')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

In this example, we are making a GET request to the /api/users endpoint. If the request is successful, the response data will be logged to the console. If there is an error, it will also be logged to the console.

Error Handling

It's important to handle errors properly in your Axios requests. You can do this using the catch method, as shown in the previous examples. You can also use the catch method to handle specific errors. For example, you might want to handle a 404 error differently than a 500 error.

axios.get('/api/users')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

In this example, we are using the error.response object to log the data, status code, and headers of the response. We are also logging the error.request object, which is the request that was made. Finally, we are logging the error.config object, which contains the config that was used to make the request.

Setting Default Options

You can set default options for all of your Axios requests by creating an instance of the Axios library with the default options.

const axios = require('axios');

const instance = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 1000,
  headers: {
    'Authorization': 'Bearer abc123'
  }
});

instance.get('/users')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

In this example, we are creating an instance of Axios with a base URL of https://api.example.com, a timeout of 1000 milliseconds, and an Authorization header with a bearer token. Any requests made with this instance will have these default options applied.

Cancelling Requests

You can cancel an Axios request by using the CancelToken object. This is useful if you need to cancel a request that is taking too long, or if you no longer need the response of a request.

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/api/users', {
  cancelToken: source.token
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (axios.isCancel(error)) {
      console.log('Request cancelled', error.message);
    } else {
      console.log(error);
    }
  });

// cancel the request (the message parameter is optional)
source.cancel('Operation cancelled by the user.');

In this example, we are creating a CancelToken object and a source object. We are then passing the source.token to the cancelToken option of the Axios request. To cancel the request, we call the cancel method on the source object. The isCancel method is used to check if the error is a cancellation error.

Using Axios with Async/Await

You can use Axios with async/await to make your code more readable and easier to work with. Here is an example of an async function that makes an Axios request:

async function getUsers() {
  try {
    const response = await axios.get('/api/users');
    console.log(response.data);
  } catch (error) {
    console.log(error);
  }
}

getUsers();

In this example, we are using the await keyword to wait for the Axios request to resolve before logging the response data to the console. If there is an error, it will be caught and logged to the console.

Conclusion

In this tutorial, we went over some of the best practices for using Axios to make HTTP requests. We covered how to install Axios, make requests, customize requests, handle errors, set default options, cancel requests, and use async/await. With these skills, you should be well on your way to using Axios effectively in your projects.

Effortlessly Make Async HTTP Requests with Axios was initially published on Wednesday January 04 2023 on the Tech Dev Blog. For the latest up-to-date content, fresh out of the oven, visit https://techdevblog.io and subscribe to our newsletter!

Did you find this article valuable?

Support Tech Dev Blog by becoming a sponsor. Any amount is appreciated!