Mastering Axios: The Power of Promise-Based HTTP Requests
In this blog, we will learn about Mastering Axios: The power of promise-based HTTP Requests.
Axios provides a straightforward and powerful way to handle HTTP requests.
What is Axios
Axios is a promise-based HTTP client for JavaScript, used to send and receive data from a server via APIs. It operates seamlessly in both browser and Node.js environments.
Axios helps your web application communicate with a backend server—for example, to fetch data, send form submissions, upload files, or authenticate users
Key Features of Axios
Promise-based: Supports then, catch, and async/await.
Automatically transforms JSON data.
Axios provides simple mechanisms for managing request timeouts and cancellations.
It enables the execution of various HTTP methods, including GET, POST, PUT, and DELETE.
Common Use Cases
Fetching data from REST APIs
Submitting forms to a backend
Handling authentication (with tokens in headers)
Making secure, reliable, and configurable HTTP requests
Axios Request Structure
axios({ method: 'get', // HTTP method (get, post, put, delete, etc.) url: 'https://api.example.com/users', // Endpoint URL data: {}, // Only for POST, PUT, PATCH params: {}, // Query string parameters (for GET requests) headers: {}, // Custom headers timeout: 5000, // Request timeout in ms responseType: 'json', // Other options: 'blob', 'text', etc. auth: { username: 'yourUsername', password: 'yourPassword' } }) .then(response => { console.log('Response:', response.data); }) .catch(error => { console.error('Error:', error); });
Making HTTP Requests with Axios
To begin, we’ll explore two of the most frequently used HTTP methods: GET and POST.
GET Request: This method is commonly used to fetch information from an API. Below is an example using Axios to perform a GET request.
Ex:
axios.get('https://jsonplaceholder.typicode.com/posts') .then(response => { console.log(response.data); // Data received from server }) .catch(error => { console.error('Error:', error); });
POST Request: This method is used to submit data to a server. Here’s an example of how Axios can send data using a POST request.
Ex:
axios.post('https://api.example.com/submit', { name: 'John Doe' email: 'john@example.com' }) .then(response => { console.log('Data posted successfully:', response.data); }) .catch(error => { console.error('Post error:', error); });
Handling Errors in Axios
When using Axios to make HTTP requests, error handling is a critical part of the development process. Errors can occur due to:
Server-side issues (e.g., 404, 500)
Network problems
Incorrect request configurations
Client-side timeouts
Ex:
axios.get("https://jsonplaceholder.typicode.com/invalid-endpoint") .catch((error) => { if (error.response) { // Server responded with a status other than 2xx console.log("Response error:", error.response); } else if (error.request) { // No response was received console.log("Request error:", error.request); } else { console.log("Error:", error.message);
}
})
Best Practices for Using Axios in React
Using async/await with Axios helps simplify asynchronous HTTP requests
const fetchData = async () => { try { const response = await axios.get('https://jsonplaceholder.typicode.com/posts'); setData(response.data); } catch (error) { setError(error.message); } };
Response Objects in Axios
When you make a request to the server, it responds with an object containing several key properties:
data: This contains the actual payload sent by the server, usually formatted as JSON, which Axios automatically parses into a JavaScript object.
status: The HTTP status code that indicates the result of your request
statusText: A descriptive message accompanying the HTTP status code.
headers: An object containing all the HTTP headers returned by the server.
config: original request configuration.
request: actual XMLHttpRequest object.
Error Object
If the request encounters an issue, the promise will be rejected and return an error object containing the following properties.
message: Error message text.
response: Response object (if received).
request: The real XMLHttpRequest instance used by the browser during the HTTP call.
config: Original request configuration.
Conclusion:
Axios offers a clean, powerful, and customizable solution for managing HTTP requests. Whether you’re building a single-page app, integrating with third-party services, or creating a Node.js backend, Axios simplifies communication with APIs and enhances maintainability.