Axios

Axios #

Axios is a popular HTTP client for Node.js and browsers, widely used for making HTTP requests to external resources such as APIs. It provides a simple and expressive API, making it easy to send HTTP requests and handle responses. Here’s a basic overview of using Axios in Node.js:

Installation: #

Install Axios using npm:

npm install axios

Making GET Requests: #

Use Axios to make a simple GET request:

const axios = require('axios');

axios.get('https://jsonplaceholder.typicode.com/posts/1')
    .then((response) => {
        console.log('Response:', response.data);
    })
    .catch((error) => {
        console.error('Error:', error.message);
    });

Passing Parameters: #

Include parameters in the request for query strings:

axios.get('https://jsonplaceholder.typicode.com/posts', {
    params: {
        userId: 1,
        _limit: 5,
    },
})
    .then((response) => {
        console.log('Response:', response.data);
    })
    .catch((error) => {
        console.error('Error:', error.message);
    });

Making POST Requests: #

Send data in a POST request:

axios.post('https://jsonplaceholder.typicode.com/posts', {
    title: 'foo',
    body: 'bar',
    userId: 1,
})
    .then((response) => {
        console.log('Response:', response.data);
    })
    .catch((error) => {
        console.error('Error:', error.message);
    });

Handling Response: #

Access response data and status:

axios.get('https://jsonplaceholder.typicode.com/posts/1')
    .then((response) => {
        console.log('Status:', response.status);
        console.log('Response Data:', response.data);
    })
    .catch((error) => {
        console.error('Error:', error.message);
    });

Handling Errors: #

Axios automatically rejects promises on HTTP error responses (e.g., status codes 4xx and 5xx):

axios.get('https://jsonplaceholder.typicode.com/nonexistent')
    .then((response) => {
        console.log('Response Data:', response.data);
    })
    .catch((error) => {
        console.error('Error:', error.message);
        console.error('Status:', error.response.status);
    });

Setting Headers: #

Customize headers for the request:

axios.post('https://jsonplaceholder.typicode.com/posts', {
    title: 'foo',
    body: 'bar',
    userId: 1,
}, {
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
    },
})
    .then((response) => {
        console.log('Response:', response.data);
    })
    .catch((error) => {
        console.error('Error:', error.message);
    });

Configuring Axios Instances: #

Create and configure Axios instances for consistent settings across requests:

const instance = axios.create({
    baseURL: 'https://jsonplaceholder.typicode.com',
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json',
    },
});

instance.get('/posts/1')
    .then((response) => {
        console.log('Response:', response.data);
    })
    .catch((error) => {
        console.error('Error:', error.message);
    });

Interceptors: #

Use interceptors for request and response transformations:

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

axios.interceptors.response.use((response) => {
    // Modify response data before resolving
    return response;
}, (error) => {
    // Handle response error
    return Promise.reject(error);
});

Cancellation: #

Axios supports cancellation of requests using the Cancel Token:

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

axios.get('/user/123', {
    cancelToken: source.token,
})
    .then((response) => {
        console.log('Response:', response.data);
    })
    .catch((error) => {
        if (axios.isCancel(error)) {
            console.log('Request canceled:', error.message);
        } else {
            console.error('Error:', error.message);
        }
    });

// Cancel the request
source.cancel('Request canceled by the user');
Axios simplifies the process of making HTTP requests in Node.js, providing a clean and intuitive API for handling various HTTP methods, parameters, and response data. Its versatility, promise-based approach, and features like interceptors make it a popular choice for developers working on both server-side and client-side applications in JavaScript and TypeScript.

Happy coding!
Published on