Understanding how to make HTTP requests and work with APIs is crucial for modern web development. You can use the Fetch API or libraries like Axios to interact with web services and retrieve or send data.

Fetch API

The Fetch API provides a modern way to make HTTP requests and handle responses in JavaScript.

Basic Usage:

  // Making a GET request
fetch('https://api.example.com/data')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('There was a problem with the fetch operation:', error);
    });
  

POST Request:

  // Making a POST request
fetch('https://api.example.com/data', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        name: 'John Doe',
        age: 30
    })
})
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('There was a problem with the fetch operation:', error);
    });
  

Handling Different Response Types:

  fetch('https://api.example.com/data')
    .then(response => response.text()) // For plain text response
    .then(text => {
        console.log(text);
    })
    .catch(error => {
        console.error('There was a problem with the fetch operation:', error);
    });
  

Axios

Axios is a popular promise-based library for making HTTP requests, providing an easier and more concise syntax compared to Fetch.

Installation:

You can install Axios using npm or include it via a CDN.

  npm install axios
  

Basic Usage:

  const axios = require('axios');

// Making a GET request
axios.get('https://api.example.com/data')
    .then(response => {
        console.log(response.data);
    })
    .catch(error => {
        console.error('There was a problem with the axios request:', error);
    });
  

POST Request:

  axios.post('https://api.example.com/data', {
    name: 'John Doe',
    age: 30
}, {
    headers: {
        'Content-Type': 'application/json'
    }
})
    .then(response => {
        console.log(response.data);
    })
    .catch(error => {
        console.error('There was a problem with the axios request:', error);
    });
  

Handling Errors:

Axios provides a more detailed error object compared to Fetch, making it easier to handle different types of errors.

  axios.get('https://api.example.com/data')
    .then(response => {
        console.log(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('Error response:', error.response.data);
            console.error('Error status:', error.response.status);
            console.error('Error headers:', error.response.headers);
        } else if (error.request) {
            // The request was made but no response was received
            console.error('Error request:', error.request);
        } else {
            // Something happened in setting up the request that triggered an Error
            console.error('Error message:', error.message);
        }
    });