Category: 05. Axios

https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ2jxQoVNx-WIU4Bl5mjNofE61lEyjSt_mknw&s

  • Handling Errors

    Axios provides detailed error information, including response status codes, which helps in error handling:

    axios.get('https://jsonplaceholder.typicode.com/invalid-url')
      .then(response => {
    
    console.log('Data:', response.data);
    }) .catch(error => {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.error('Response Error:', error.response.status);
      console.error('Response Data:', error.response.data);
    } else if (error.request) {
      // The request was made but no response was received
      console.error('Request Error:', error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.error('Error Message:', error.message);
    }
    });
  • Configurations and Defaults

    You can set default configurations for Axios, which will apply to all requests:

    axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
    axios.defaults.headers.common['Authorization'] = 'Bearer YOUR_TOKEN';
    
    // Making a request with default configurations
    axios.get('/posts')
      .then(response => {
    
    console.log('Data:', response.data);
    });
  • Cancel Requests

    You can cancel a request if needed using the CancelToken:

    const CancelToken = axios.CancelToken;
    const source = CancelToken.source();
    
    axios.get('https://jsonplaceholder.typicode.com/posts', {
      cancelToken: source.token
    })
      .then(response => {
    
    console.log('Data:', response.data);
    }) .catch(thrown => {
    if (axios.isCancel(thrown)) {
      console.log('Request canceled', thrown.message);
    } else {
      console.error('Error:', thrown);
    }
    }); // Cancel the request source.cancel('Operation canceled by the user.');
  • Interceptors

    Interceptors allow you to run your code or modify the request/response before they are handled:

    // Add a request interceptor
    axios.interceptors.request.use(config => {
      // Modify the request config
      config.headers['Authorization'] = 'Bearer YOUR_TOKEN';
      return config;
    }, error => {
      return Promise.reject(error);
    });
    
    // Add a response interceptor
    axios.interceptors.response.use(response => {
      // Modify the response data
      return response.data;
    }, error => {
      return Promise.reject(error);
    });
    
  • Sending Data with POST Requests

    To send data to a server, you can use a POST request. Here’s how you can send JSON data:

    axios.post('https://jsonplaceholder.typicode.com/posts', {
      title: 'foo',
      body: 'bar',
      userId: 1
    })
      .then(response => {
    
    console.log('Data:', response.data);
    console.log('Status:', response.status);
    }) .catch(error => {
    console.error('Error:', error);
    });
  • Using Async/Await

    For cleaner asynchronous code, you can use async/await:

    async function fetchData() {
      try {
    
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
    console.log('Data:', response.data);
    console.log('Status:', response.status);
    } catch (error) {
    console.error('Error:', error);
    } } fetchData();
  • Basic Usage

    Here’s a basic example of how to use Axios to make a GET request and handle the response:

    // Import Axios if using Node.js or a module bundler
    // const axios = require('axios');
    
    // Making a GET request
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
    
    console.log('Data:', response.data);
    console.log('Status:', response.status);
    }) .catch(error => {
    console.error('Error:', error);
    });
  • Setting Up Axios

    To get started with Axios, you need to install it. If you’re working in a Node.js environment or using a module bundler like Webpack or Parcel, you can install Axios via npm or yarn:

    npm install axios
    

    or

    yarn add axios
    

    In a browser environment, you can include Axios via a CDN. Add the following script tag to your HTML:

    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    
  • Key Features

    1. Promise-Based: Axios uses promises, which means you can use async/await for easier asynchronous code.
    2. Intercept Requests and Responses: Axios allows you to intercept requests or responses before they are handled by then or catch.
    3. Transform Requests and Responses: You can transform the data before sending it or after receiving it.
    4. Cancel Requests: Axios supports request cancellation using the CancelToken.
    5. Automatic JSON Data Transformation: Axios automatically transforms JSON data, so you don’t need to manually parse the response.
    6. Browser and Node.js Support: It works both in the browser and on the server side with Node.js.
  • Introduction to Axios

    Axios is a promise-based HTTP client for JavaScript. It allows you to make requests to servers and handle responses in a straightforward way. Axios supports all modern browsers and Node.js, making it versatile for both front-end and back-end development.