How do I make an HTTP request in Javascript?

make an HTTP request in Javascript

In JavaScript, you can make HTTP requests using different methods and APIs. The most common ones are using the XMLHttpRequest object (older approach) and the fetch API (modern approach). Here’s how to make HTTP requests using both methods:

  1. Using XMLHttpRequest (older approach): The XMLHttpRequest object is widely supported in older browsers but is less user-friendly compared to the newer fetch API.
javascriptCopy code// Create an XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Configure the HTTP request (GET request to a URL)
xhr.open('GET', 'https://api.example.com/data', true);

// Set up a callback function to handle the response
xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      // Request successful, process the response
      var data = JSON.parse(xhr.responseText);
      console.log(data);
    } else {
      // Request failed, handle the error
      console.error('Request failed with status:', xhr.status);
    }
  }
};

// Send the request
xhr.send();

  1. Using fetch API (modern approach): The fetch API provides a simpler and more modern way to make HTTP requests. It returns a Promise, making it easier to work with async/await.
javascriptCopy code// Make a GET request using fetch
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Request failed with status:', response.status);
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

  1. Using async/await (modern approach with async/await): With async/await, you can write asynchronous code in a more synchronous style.
javascriptCopy codeasync function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error('Request failed with status:', response.status);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

fetchData();

Choose the method that best fits your needs and consider browser compatibility when deciding which approach to use. The fetch API is generally recommended for modern applications due to its simplicity and flexibility.

You might also like our TUTEZONE section which contains exclusive tutorials on making your life simpler by using technology.

Recommended For You

About the Author: Ranjit Ranjan

More than 15 years of experience in web development projects in countries such as US, UK and India. Blogger by passion and SEO expert by profession.