CodeGym /Courses /Frontend SELF EN /Axios and Fetch

Axios and Fetch

Frontend SELF EN
Level 44 , Lesson 0
Available

5.1 Fetch API

For making HTTP requests in JavaScript, two libraries are commonly used: the built-in fetch function and the external Axios library. Both offer powerful and flexible capabilities for interacting with APIs and other web resources.

Fetch API is a built-in way in browsers to make HTTP requests. It's based on promises and provides a flexible and modern approach to handling network requests.

Simple fetch request syntax:

    
      let promise = fetch(url, {method, headers,
        body})
    
  

Main Fetch concepts:

  • fetch(url, options): the main method for making HTTP requests
  • Returns a promise that resolves to a Response object

Example of a simple GET request using Fetch:

JavaScript
    
      fetch('https://jsonplaceholder.typicode.com/posts/1')
        .then(response => {
          if (!response.ok) {
            throw new Error('Network error: received an incorrect response from the server');
          }
          return response.json();
        })
        .then(data => {
          console.log(data);
        })
        .catch(error => {
          console.error('Request error: ', error);
        });
    
  

Example of a POST request using Fetch:

JavaScript
    
      fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          title: 'foo',
          body: 'bar',
          userId: 1
        })
      })
        .then(response => response.json())
        .then(data => {
          console.log(data);
        })
        .catch(error => {
          console.error('Request error: ', error);
        });
    
  

Fetch Settings

Fetch API allows configuring various request parameters through the options object, such as method, headers, request body, and more.

JavaScript
    
      const options = {
        method: 'GET', // or 'POST', 'PUT', 'DELETE', etc.
        headers: {
          'Content-Type': 'application/json'
        },
        // body: JSON.stringify(data) // used for POST and PUT requests
      };

      fetch('https://jsonplaceholder.typicode.com/posts/1', options)
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.error('Request error: ', error));
    
  

5.2 Axios Library

Axios is a popular library for making HTTP requests in JavaScript. It offers a more convenient and functional API compared to the native Fetch API and supports many additional features, such as automatic JSON conversion, timeout handling, request cancellation, and support for older browsers.

Installing Axios

Axios can be installed via npm or included through a CDN.

Installation via npm:

Terminal
    
      npm install axios
    
  

Using in Node.js or with module bundlers (e.g., Webpack):

JavaScript
    
      // For CommonJS
      const axios = require('axios');

      // For ES6 modules
      import axios from 'axios';
    
  

Including via CDN in the browser:

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

Simple GET request syntax:

    
      let promise = axios.get(url)
    
  

Simple POST request syntax:

    
      let promise = axios.post(url, data, config)
    
  

Main Axios concepts:

  • axios(config): the main method for making HTTP requests
  • Takes a configuration object, which can include url, method, headers, data, and other parameters.
  • Shortcut methods: Axios provides methods for each HTTP method (axios.get, axios.post, axios.put, axios.delete, etc.), simplifying the execution of corresponding requests.
  • Promises: all Axios methods return a Promise that resolves to the response object or is rejected in case of an error.

Simple GET request syntax with response and error handling:

JavaScript
    
      axios.get(url)
        .then(response => {
          // Handle successful response
        })
        .catch(error => {
          // Handle error
        });
    
  

Simple POST request syntax with response and error handling:

JavaScript
    
      axios.post(url, data, config)
        .then(response => {
          // Handle successful response
        })
        .catch(error => {
          // Handle error
        });
    
  

Example of a simple GET request using Axios:

HTML
    
      <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    
  
JavaScript
    
      axios.get('https://jsonplaceholder.typicode.com/posts/1')
        .then(response => {
          console.log(response.data);
        })
        .catch(error => {
          console.error('Request error: ', error);
        });
    
  

Example of a POST request using Axios:

HTML
    
      <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    
  
JavaScript
    
      axios.post('https://jsonplaceholder.typicode.com/posts', {
          title: 'foo',
          body: 'bar',
          userId: 1
        })
        .then(response => {
          console.log(response.data);
        })
        .catch(error => {
          console.error('Request error: ', error);
        });
    
  

5.3 Configuring Axios

Axios Settings

Axios lets you configure HTTP requests via the config object, which includes parameters like url, method, headers, and data (data). Here's a basic example of request configuration:

HTML
    
      <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    
  
JavaScript
    
      const config = {
        method: 'get', // can be 'get', 'post', 'put', 'delete', etc.
        url: 'https://jsonplaceholder.typicode.com/posts/1',
        headers: {
          'Content-Type': 'application/json' // Header to specify data type
        },
        // data: JSON.stringify(data) // Used for POST and PUT requests to pass request body
      };

      axios(config)
        .then(response => console.log(response.data))
        .catch(error => console.error('Request error: ', error));
    
  

Additional Axios Features:

  1. Query parameters: can be passed in the URL.
  2. Request cancellation: using AbortController.
  3. Timeouts: setting a waiting time for the request.

Example of using query parameters:

HTML
    
      <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    
  
JavaScript
    
      axios.get('https://jsonplaceholder.typicode.com/posts', {
        params: {
          userId: 1 // Query parameters are passed via the params object
        }
      })
        .then(response => {
          console.log(response.data);
        })
        .catch(error => {
          console.error('Request error: ', error);
        });
    
  

5.4 Comparing Fetch and Axios

Let's compare Fetch and Axios based on key metrics:

1. Ease of Use:

  • Fetch: easy to use for basic operations but requires additional handling for complex scenarios (e.g., JSON transformation, timeout handling).
  • Axios: offers a more convenient and powerful API for performing complex requests.

2. JSON Support:

  • Fetch: requires explicit response.json() call to parse the response body to JSON.
  • Axios: automatically parses JSON responses.

3. Timeouts:

  • Fetch: no built-in support for timeouts. Timeout implementation requires using AbortController or wrappers.
  • Axios: supports timeout configuration.

4. Interceptors:

  • Fetch: does not support request and response interceptors.
  • Axios: allows the use of interceptors to perform logic before and after sending a request.

Example of interceptors in Axios

Interceptors allow performing specific actions before sending a request or after receiving a response:

HTML
    
      <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    
  
JavaScript
    
      // Adding a request interceptor
      axios.interceptors.request.use(config => {
        console.log('Request sent to server: ', new Date());
        return config;
      }, error => {
        return Promise.reject(error);
      });

      // Adding a response interceptor
      axios.interceptors.response.use(response => {
        console.log('Response received from server: ', new Date());
        return response;
      }, error => {
        return Promise.reject(error);
      });

      // Example request with interceptors
      axios.get('https://jsonplaceholder.typicode.com/todos/1')
        .then(response => console.log(response.data))
        .catch(error => console.error('Request error: ', error));
    
  

Parallel Requests with Axios

Using Axios, you can easily make parallel requests and handle the results with Promise.all():

HTML
    
      <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    
  
JavaScript
    
      Promise.all([
        axios.get('https://jsonplaceholder.typicode.com/todos/1'),
        axios.get('https://jsonplaceholder.typicode.com/todos/2')
      ])
      .then(responses => {
        responses.forEach(response => {
          console.log(response.data);
        });
      })
      .catch(error => console.error('Request error: ', error));
    
  
1
Task
Frontend SELF EN, level 44, lesson 0
Locked
Fetching Data with Axios
Fetching Data with Axios
1
Task
Frontend SELF EN, level 44, lesson 0
Locked
Sending Data with Fetch
Sending Data with Fetch
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION