Simple HTTP requests in JavaScript using Axios

As a full-stack developer, you often need to make HTTP requests to interact with APIs and fetch data from servers. While modern browsers provide the native Fetch API for making requests, it can be quite verbose and lacks some advanced features. This is where Axios comes in handy.

Axios is a popular, promise-based HTTP client for JavaScript that works in both browsers and Node.js. It provides a simple, clean API for making requests and handles a lot of the complexity behind the scenes. In this guide, I‘ll walk you through how to get started with Axios and make HTTP requests with ease.

What is Axios?

Axios is a lightweight library that provides an easy-to-use API for sending asynchronous HTTP requests to REST endpoints. It is built on top of the native XMLHttpRequests and Promises. Some key features of Axios include:

  • Make XMLHttpRequests from the browser or Node.js
  • Supports the Promise API
  • Intercept request and response data
  • Cancel requests
  • Automatic transformations for JSON data
  • Client-side protection against XSRF

With an intuitive API and excellent documentation, Axios greatly simplifies the process of making HTTP requests compared to native APIs like XMLHttpRequests or the newer Fetch API.

Installing Axios

Before you can start using Axios, you need to include it in your project. There are a few different ways to do this:

Using npm:

npm install axios

Using yarn:

yarn add axios

Including via a CDN:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Once installed, you can import Axios into your JavaScript file:

// ES6 import syntax
import axios from ‘axios‘;

// Require syntax 
const axios = require(‘axios‘);

Now you‘re ready to start making requests!

Making GET Requests

GET is the most common type of HTTP request. It is used to retrieve data from a specified resource. With Axios, making a GET request is straightforward.

Here‘s a simple example that fetches a list of users from an API:

const getUsers = async () => {
  try {
    const response = await axios.get(‘https://jsonplaceholder.typicode.com/users‘);
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

getUsers();

In this example, we define an async function called getUsers. Inside it, we use the axios.get() method to send a GET request to the specified URL.

Axios uses Promises under the hood, so the most convenient way to work with the response is using the async/await syntax as shown above. This lets us write the code in a more synchronous and readable manner.

The response object returned by Axios contains a lot of useful information in addition to the actual data. Some important properties are:

  • data – the payload returned from the server
  • status – the HTTP code returned from the server
  • statusText – the HTTP status message returned by the server
  • headers– the headers sent by server
  • config – the original request configuration
  • request – the request object

If you prefer to use the traditional promise .then() syntax instead of async/await, you can do:

const getUsers = () => {
  axios.get(‘https://jsonplaceholder.typicode.com/users‘)
    .then(response => {
      console.log(response.data);
    })
    .catch(error => {
      console.log(error);
    });
}

Passing Parameters to GET Requests

You can pass parameters to a GET request in a few different ways with Axios.

One common way is to use a query string in the URL:

axios.get(‘https://jsonplaceholder.typicode.com/users?_limit=5‘)

In this example, _limit=5 is passed as a query parameter to limit the number of results to 5.

Alternatively, you can use the params property in the config object:

axios.get(‘https://jsonplaceholder.typicode.com/users‘, {
  params: {
    _limit: 5
  }
})

Axios will automatically serialize the params object to a query string and append it to the URL.

Making POST Requests

While GET requests are used to fetch data, POST requests are used to submit data to be processed to a specified resource.

Here‘s an example of how to make a POST request with Axios to create a new user:

axios.post(‘https://jsonplaceholder.typicode.com/users‘, {
  name: ‘John Doe‘,
  email: ‘[email protected]‘
})
.then(response => {
  console.log(response.data);
});

The axios.post method takes the URL as the first argument and the request payload as the second argument. This payload will be sent in the body of the request.

Just like with GET requests, you can use async/await instead of .then() for a cleaner syntax:

const createUser = async () => {
  try {
    const response = await axios.post(‘https://jsonplaceholder.typicode.com/users‘, {
      name: ‘John Doe‘,  
      email: ‘[email protected]‘
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

createUser();

Other HTTP Methods

In addition to GET and POST, Axios provides methods for all the other HTTP verbs:

  • axios.put() – for updating existing resources
  • axios.patch() – for partially modifying a resource
  • axios.delete() – for deleting a resource
  • axios.options() – for retrieving information about a resource

They all follow the same pattern as get and post – the URL is passed as the first argument and the request payload, if any, is passed as the second argument.

For example, here‘s how you can use axios.put() to update a user:

axios.put(‘https://jsonplaceholder.typicode.com/users/1‘, {
  name: ‘Jane Doe‘,
  email: ‘[email protected]‘  
})

Config Options

So far, we‘ve seen how to specify the HTTP method, URL and request payload. But Axios provides many other config options to customize your requests. Some commonly used ones are:

  • baseURL – prepend a base URL to all requests
  • headers – set custom request headers
  • timeout – set a timeout (in milliseconds) for the request
  • auth – set HTTP basic auth
  • responseType – indicate the type of data that the server will respond with
  • xsrfCookieName – change the name of the XSRF token cookie
  • xsrfHeaderName – change the name of the XSRF token header

Here‘s an example of setting some custom headers:

const options = {
  headers: {‘X-Custom-Header‘: ‘example‘}
};

axios.post(‘https://jsonplaceholder.typicode.com/users‘, {
  name: ‘John Doe‘  
}, options);

You can set default config options that will be applied to all requests:

axios.defaults.baseURL = ‘https://api.example.com‘;
axios.defaults.headers.common[‘Authorization‘] = AUTH_TOKEN;
axios.defaults.headers.post[‘Content-Type‘] = ‘application/x-www-form-urlencoded‘;

Handling Responses

Once the server responds to your request, Axios returns a promise that resolves to a response object. This object contains all sorts of useful information in addition to the actual data.

Some key properties of the response object are:

  • data – the payload returned from the server
  • status – the HTTP code returned from the server
  • statusText – the HTTP status message returned by the server
  • headers – the headers sent by server
  • config – the original request configuration
  • request – the request object

You can access these in the .then callback:

axios.get(‘https://jsonplaceholder.typicode.com/users‘)
  .then(response => {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
  })

Or using async/await:

const getUsers = async () => { 
  const response = await axios.get(‘https://jsonplaceholder.typicode.com/users‘);
  console.log(response.data);
  console.log(response.status);
  console.log(response.statusText); 
  console.log(response.headers);
}

getUsers();

Handling Errors

Axios throws an error when the server returns an error code (4xx or 5xx). You can catch this error in a .catch block:

axios.get(‘https://jsonplaceholder.typicode.com/404‘)
  .then(response => {
    // This will not execute
  })  
  .catch(error => {
    if (error.response) {
      // The request was made and the server responded with an error status code
      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
      console.log(error.request);
    } else {
      // An error occurred while setting up the request  
      console.log(‘Error‘, error.message);
    }
  });

Or with async/await:

const getUser = async () => {
  try {
    const response = await axios.get(‘https://jsonplaceholder.typicode.com/404‘);
  } 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);
    }
  }
}

getUser();

Interceptors

Axios interceptors allow you to intercept requests or responses before they are handled by .then or .catch. They are useful for tasks such as logging or transforming requests/responses.

Here‘s an example of adding a request interceptor:

axios.interceptors.request.use(
  config => {
    // Modify the config here 
    return config;
  },
  error => {
    // Handle request errors here
    return Promise.reject(error);
  }
);

And a response interceptor:

axios.interceptors.response.use(
  response => {
    // Modify the response here
    return response;
  }, 
  error => {
    // Handle response errors here
    return Promise.reject(error);
  }
);

You can also remove an interceptor using the eject method:

const myInterceptor = axios.interceptors.request.use(() => {});
axios.interceptors.request.eject(myInterceptor);

Axios vs Fetch API

The Fetch API is a modern native browser API for making asynchronous HTTP requests, similar to XMLHttpRequest (XHR). While it provides a good basic feature set, it lacks some key functionality compared to Axios:

  • No request/response interceptors
  • No timeouts
  • No built-in XSRF protection
  • No ability to cancel requests
  • No built-in transform request/response data
  • Requires manual transformation of data to JSON

Axios addresses these shortcomings and provides a more feature-rich and convenient experience. It‘s a good choice if you need a full-featured HTTP client with strong browser support.

However, if you‘re working on a simple project with limited browser support requirements, the Fetch API can be a good choice to avoid adding another dependency.

Using with Node.js

Axios can be used in Node.js, allowing you to easily make HTTP requests to external services. The API is the same as in the browser.

First, install Axios in your Node project:

npm install axios

Then you can use it in your Node scripts:

const axios = require(‘axios‘);

axios.get(‘https://jsonplaceholder.typicode.com/users‘)
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

Browser Support

Axios has excellent browser support, working in all modern browsers and even in IE8 and higher. It makes use of the ES6 Promise API, which is available in all modern browsers, but requires a polyfill for IE.

If you need to support older browsers, you can include a Promise polyfill before including Axios:

<script src="https://polyfill.io/v3/polyfill.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Conclusion

In this guide, we‘ve covered the basics of using Axios for making HTTP requests in JavaScript. We‘ve seen how to install Axios, make GET and POST requests, handle responses and errors, and use some of the more advanced features like config options and interceptors.

Axios provides a clean, promise-based API for making HTTP requests that works consistently across browsers and Node.js. It abstracts away many of the complexities of the native APIs, providing a more enjoyable developer experience.

Whether you‘re just getting started with HTTP requests in JavaScript or looking for a more feature-rich alternative to the Fetch API, Axios is definitely worth considering in your next project.

Similar Posts

Leave a Reply

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