JavaScript Axios

Axios is a popular JavaScript library used to make HTTP requests from the browser and Node.js. It provides a simple and intuitive API to perform various types of HTTP requests like GET, POST, PUT, DELETE, and more. Axios is promise-based, which allows for easy handling of asynchronous operations and error handling.

Setting Up Axios

To use Axios in your project, you can include it via a CDN or install it using npm.

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

Basic Usage

Below are some basic examples of using Axios to make HTTP requests.

GET Request
Try yourself
        
            // Making a GET request
axios.get('https://api.example.com/data')
    .then(response => {
        console.log(response.data);
    })
    .catch(error => {
        console.error('Error fetching data:', error);
    });
        
    

This example demonstrates how to make a GET request using Axios to fetch data from a URL.


POST Request
Try yourself
        
            // Making a POST request
axios.post('https://api.example.com/data', {
    name: 'John Doe',
    age: 30
})
.then(response => {
    console.log('Data posted:', response.data);
})
.catch(error => {
    console.error('Error posting data:', error);
});
        
    

This example shows how to make a POST request using Axios to send data to a server.


Handling Responses

Try yourself
        
            // Handling responses
axios.get('https://api.example.com/data')
    .then(response => {
        if (response.status === 200) {
            console.log('Data fetched successfully:', response.data);
        } else {
            console.log('Unexpected response status:', response.status);
        }
    })
    .catch(error => {
        console.error('Error fetching data:', error);
    });
        
    

This example demonstrates how to handle responses from an Axios request.


Error Handling

Try yourself
        
            // Handling errors
axios.get('https://api.example.com/data')
    .then(response => {
        console.log('Data fetched successfully:', response.data);
    })
    .catch(error => {
        if (error.response) {
            // Server responded with a status other than 200 range
            console.error('Error response:', error.response.data);
        } else if (error.request) {
            // No response was received
            console.error('No response received:', error.request);
        } else {
            // Error setting up the request
            console.error('Error setting up request:', error.message);
        }
    });
        
    

This example shows how to handle errors when making requests using Axios.


Setting Headers

You can set custom headers for your Axios requests.

Try yourself
        
            // Setting headers
axios.get('https://api.example.com/data', {
    headers: {
        'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
        'Content-Type': 'application/json'
    }
})
.then(response => {
    console.log(response.data);
})
.catch(error => {
    console.error('Error fetching data with headers:', error);
});
        
    

This example demonstrates how to set custom headers in Axios requests.


Uploading Files

Axios can be used to upload files to a server.

Try yourself
        
            // Uploading a file
const formData = new FormData();
formData.append('file', fileInput.files[0]);

axios.post('https://api.example.com/upload', formData, {
    headers: {
        'Content-Type': 'multipart/form-data'
    }
})
.then(response => {
    console.log('File uploaded successfully:', response.data);
})
.catch(error => {
    console.error('Error uploading file:', error);
});
        
    

This example shows how to upload files using Axios.


Request Cancellation

Axios supports request cancellation using the CancelToken API.

Try yourself
        
            // Canceling a request
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('https://api.example.com/data', {
    cancelToken: source.token
})
.then(response => {
    console.log(response.data);
})
.catch(error => {
    if (axios.isCancel(error)) {
        console.log('Request canceled:', error.message);
    } else {
        console.error('Error fetching data:', error);
    }
});

// Cancel the request
source.cancel('Operation canceled by the user.');
        
    

This example demonstrates how to cancel a request using Axios.


Advanced Usage

Axios also provides advanced features such as interceptors, request/response transformation, and more.

Using Interceptors
Try yourself
        
            // Adding interceptors
axios.interceptors.request.use(request => {
    console.log('Starting Request', request);
    return request;
});

axios.interceptors.response.use(response => {
    console.log('Response:', response);
    return response;
});
        
    

This example demonstrates how to use interceptors to modify requests and responses.


Request and Response Transformation
Try yourself
        
            // Transforming requests and responses
axios({
    method: 'post',
    url: 'https://api.example.com/data',
    data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
    },
    transformRequest: [(data, headers) => {
        // Transform the request data here
        data = JSON.stringify(data);
        return data;
    }],
    transformResponse: [(data) => {
        // Transform the response data here
        data = JSON.parse(data);
        return data;
    }]
}).then(response => {
    console.log('Transformed response:', response.data);
});
        
    

This example shows how to transform requests and responses using Axios.


Important Notes

Here are some important notes and best practices when using Axios:


Summary

Axios is a powerful and easy-to-use library for making HTTP requests in JavaScript. By understanding and using Axios, you can simplify the process of communicating with servers and handling data in your applications.