Axios Unveiled : Insights from My Beginner’s Journey

Introduction:

coderandcreator
5 min readDec 5, 2023

--

Axios is a popular library used for making HTTP requests in JavaScript. As a beginner, working with Axios can seem daunting, especially when you’re trying to make sense of all the configuration options and promise-based syntax. In this blog post, I’ll share my personal experience of learning Axios and provide some tips and tricks that helped me along the way.

Getting Started:

Before diving into the depths of Axios, it’s essential to understand the basics of HTTP requests. Familiarize yourself with terms like GET, POST, PUT, DELETE, headers, query parameters, and JSON data. Once you have a good grasp of these concepts, you can start exploring Axios.

Installation:

To get started with Axios, you need to install it in your project. You can do this by running the following command in your terminal:

npm install axios

Configuration:

The first step in using Axios is configuring it correctly. Axios provides several configuration options, such as baseURL, timeout, method, headers, and responseType. Understanding these options is crucial for making successful requests.

baseURL: This option sets the base URL for all requests. It’s useful when you want to make requests to a server with a different domain name.

timeout: Specifies the time in milliseconds before the request times out. Useful when dealing with slow networks or servers.

method: Defines the HTTP method (GET, POST, PUT, DELETE, etc.) for the request.

headers: An object containing key-value pairs of headers to be sent with the request.

responseType: Specifies the type of response expected from the server. By default, Axios expects a JSON response.

Here’s an example configuration:

axios.create({
baseURL: 'https://api.example.com',
timeout: 1000,
headers: {
'Content-Type': 'application/json'
},
responseType: 'json'
});

Making Requests:

Now that you have configured Axios, let’s move on to making requests. There are four main methods for sending requests: get, post, put, and delete. Each method has its own set of configurations and uses.

get(): Retrieves data from a specified URL.

post(): Creates a new resource on the server using data provided in the request body.

put(): Updates an existing resource on the server using data provided in the request body.

delete(): Deletes a resource from the server.

Here’s an example of get request:

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

In this example, we’re retrieving a list of users from the server. The .then() method handles the response data, while the .catch() method catches any errors that might occur during the request.

Post Requests:
Post requests are used to create a new resource on the server. They require data to be sent in the request body. Here’s an example:

const data = {
name: 'John Doe',
email: 'johndoe@example.com'
};

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

In this example, we’re creating a new user on the server with the name and email address provided in the data object.

Error Handling:

When working with Axios, error handling is crucial. Always remember to include a .catch() block to handle any potential errors that may arise during the request. The .catch() block receives the error object as a parameter, which contains information about the error that occurred.

Promises:

Axios uses promises to handle asynchronous requests. Promises allow you to work with the request data once it’s available, rather than waiting for the request to complete. They also enable chaining, which means you can handle multiple requests sequentially without worrying about blocking code execution.

Cancelling Requests :

With Axios, you can cancel pending requests using the `cancelToken` property. This comes in handy when you want to stop a request midway through, perhaps because the user changed their mind or the request is taking too long.

Here’s an example of how to cancel a request using `cancelToken`:

import axios from 'axios';

// Create a new instance of axios with a cancel token source
const axiosInstance = axios.create({
cancelToken: new axios.CancelToken((cancel) => {
// Handle cancellation
}),
});
// Make a request
axiosInstance.get('https://example.com')
.then(() => {
// Handle success
})
.catch((error) => {
// Handle error
});
// Cancel the request
axiosInstance.cancel();

In this example, we create a new instance of Axios with a cancel token source. We then make a request using the 'get' method. Finally, we call the 'cancel' method to cancel the request.

Note that the 'cancel' method returns a boolean value indicating whether the request was successfully cancelled. If the request was not cancelled, it will return 'false'.

Using Interceptors:

Interceptors are functions that run before every request is sent out. They can be used to modify the request configuration, add authentication tokens, or perform other tasks.

Here’s an example of how to use interceptors with Axios:

import axios from 'axios';

// Create a new instance of axios with an interceptor
const axiosInstance = axios.create({
interceptors: {
request: (request) => {
// Modify the request configuration
request.params. foo = 'bar';
return request;
},
response: (response) => {
// Modify the response data
response.data = response.data.toUpperCase();
return response;
},
},
});
// Make a request
axiosInstance.get('https://example.com')
.then((response) => {
// Handle success
})
.catch((error) => {
// Handle error
});

In this example, we create a new instance of Axios with an interceptor. The interceptor modifies the request configuration by adding a 'foo' parameter with the value 'bar' to the request object. It also modifies the response data by converting it to uppercase.

We then make a request using the 'get' method. The interceptor runs before the request is sent out, modifying the request configuration and response data accordingly.

Conclusion

Axios is a powerful and flexible library for making HTTP requests in JavaScript. With features like configurable request settings, promise-based API, and support for interceptors, it’s a great choice for building robust web applications.

By mastering Axios, you’ll be able to build scalable and maintainable web applications that can interact with APIs and services in a reliable and efficient manner. So go ahead, give Axios a try, and see what you can build!

For My Readers

Thank you so much for reading my blogs ❤️! I’m thrilled to have the opportunity to share my thoughts with you. I am eager to learn and improve. Your feedback is incredibly valuable to me.

If you have any thoughts or suggestions, I would love to hear them! Feel free to leave a comment below, connect with me on Twitter/Insta: @coderandcreator, or shoot me an Email: coderandcreator@gmail.com. I’m open to any insights you have to offer and am excited to continue this journey.

Once again, thank you for being part of this experience. Looking forward to connecting with you!

Best regards,
coderandcreator 👨‍💻

--

--

coderandcreator
coderandcreator

Written by coderandcreator

From Data & Security to Full-Stack Dev | I Love Writing Solutions

No responses yet