JavaScript HTTP Request with Axios

As a frontend developer, you’ll most times be required to show content on your webpage which is either stored in a database or a third-party API. To do this, you’ll need to make an HTTP request to reach out to that database/API to get the data, and then manipulate it.

The Fetch API has been the most common way for JavaScript developers to interact with APIs/databases.

Over the years, developers began migrating to Axios due to several features it offers over the Fetch API.

Axios is a promised-based JavaScript library for making HTTP requests for Node.js and the browser. It is an alternative to the JavaScript built-in Fetch API.

This article will introduce you to making JavaScript HTTP requests with Axios. At the end of the article, you will learn how to send GET, POST, and PATCH requests with Axios, use the async-await syntax, and overall get familiar with the library.

Prerequisite

To learn about Axios, you should first be familiar with JavaScript, and since Axios is an alternative to the JavaScript built-in Fetch API, a little knowledge of the Fetch API would be great.

What is Axios?

Axios is a JavaScript library for making promised-based HTTP requests from the browser or a Node.js server. Axios makes HTTP requests from the browser using the XMLHttpRequest object. Since Axios is optimized to work with promises, it is very easy to use with modern JavaScript frameworks like React, Angular, and Vue.js.

Axios has several additional features beyond simply making HTTP requests. These features include an automatic transformation of JSON data, the ability to intercept HTTP requests, client-side support for protecting against XSRF, and the ability to cancel requests.

Installation

To install Axios, you can use either npm or yarn, depending on your preferred package manager.

To install Axios, open a terminal and run the following command:

// using npm

npm install axios

// using yarn

yarn add axios

Once Axios is installed, you can import it into your JavaScript code using the following statement:

import axios from 'axios';

Once you’ve imported Axios into your project, you can then use Axios to make HTTP requests in your code. We’ll see a few examples in a while.

Using Axios over the Fetch API

You might consider using Axios over the Fetch API for many reasons. One of the most notable reasons is that Axios automatically transforms the response data into JSON, which can be very convenient. With the Fetch API, you’d have to parse the response data as JSON manually.

Also, Axios has built-in support for intercepting and modifying HTTP requests and responses using interceptors. With interceptors, you can add headers to requests, handle errors, or even modify the content of a response before it is returned to the client. Interceptors enable you to customize the behavior of Axios to meet your specific needs.

Axios supports canceling requests, which can be useful for aborting a request before it completes. The Fetch API, on the other hand, does not have this capability.

Another aspect where Axios beats the Fetch API is its wide range of browser compatibility, including older browsers like Internet Explorer 8. The Fetch API is not supported in older browsers.

Choosing to use Axios or the Fetch API will depend on your personal preferences and the requirements of your project. Axios and the Fetch API are widely used for making HTTP requests in JavaScript, and either could be a suitable option depending on your project's needs.

Axios functions

Axios offers several functions with which you can make requests. We’ll take a look at the most common ones.

Get method

The axios.get() method is used to make a GET request with Axios. The axios.get() method accepts a URL as its first argument and an optional options object as its second argument. The options object allows you to specify different settings for your request, including HTTP headers and query parameters.

Here is an example of how to make a GET request with Axios:

axios.get('https://randomuser.me/api/', {

params: {

results: 60

}

})

.then(res => {

// handle success

console.log(res);

})

.catch(error => {

// handle error

console.log(error);

});

In this example, we are making a GET request to the randomuser.me/api URL (A free, open-source API that generates random user data) and passing a query parameter called Params with a value of 60 (to specify the number of users we want).

The then() method is called when the request is successful, and it receives the response object as an argument. The catch() method is called if there is an error making the request, and it receives the error object as an argument.

Axios also supports the use of async/await syntax to make requests. This can make it easier to work with asynchronous code and can make your code look cleaner and more readable. You can also use the Get method with the async/await syntax like so:

const fetchUser = async () => {

try {

const res = await axios.get('https://randomuser.me/api/', {

params: {

results: 60

}

console.log(res)

}

catch (error) {

console.error(error);

}

}

Post Method

POST requests can be used to send data to a server to create or update a resource when working with APIs. For instance, an app could make a POST request to a messaging API to send a message to a specific user or to create a new account on a social media platform.

A POST request can send data to the server as a request payload rather than being appended to the URL as query parameters. It is mostly used to upload a file or submit a completed web form.

The post method can be used to make a POST request with Axios. This method takes two arguments; the URL of the endpoint to which the request should be sent and an object containing the data to be sent as the request payload.

Here's an example of how you might use axios.post to make a POST request:

const person = {

name: 'John Doe',

message: ‘Hello World’

};

axios.post('/api/users', person)

.then(response => {

console.log(response.data);

})

.catch(error => {

console.error(error);

});

In this example, the person object will be sent as the request payload to the /api/users endpoint. The response from the server will then be logged to the console.

Patch Method

The patch method of the axios object is used to make a PATCH request with Axios. Just like the POST method, it takes two arguments: the URL of the endpoint to which the request should be sent and an object containing the data to be sent as the request payload.

The axios.patch method allows you to specify additional configuration options for your request by including a third argument, which is an object containing these options. Within this object, you can set custom headers using the headers property, specify the expected type of the response data with the responseType property, and set a custom timeout for the request with the timeout property.

Here’s an example of how to make a PATCH request with Axios:

axios.patch(‘/items/’ + id, {

name: ‘new name’

})

.then(res => {

console.log(res)

})

.catch(error => {

console.log(error)

});

In the example, a JSON payload containing the updated name for an item is sent as a PATCH request to the /items/:id endpoint.

Conclusion

Axios is a powerful and easy-to-use JavaScript library that allows developers to make HTTP requests from a web browser. It is a popular choice for many developers due to its simplicity and flexibility. It offers several features that make it superior to other options, such as the Fetch API.

In this article, we covered Axios's installation process and how to make basic HTTP requests such as GET, POST, and PATCH using the library. If you have followed this article up until now, you should be well-equipped to get started with Axios and make HTTP requests in your projects.