Posted On May 16, 2023

How do I make an HTTP request in Javascript?

Ghazal Ehsan 0 comments
Hut Explore >> Programming , Technology >> How do I make an HTTP request in Javascript?
http requst javascript

How do I make an HTTP request in Javascript?

In JavaScript, you can make an HTTP request using the XMLHttpRequest object or the newer fetch() function. I’ll provide examples for both approaches:

Using XMLHttpRequest:

var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    var response = JSON.parse(xhr.responseText);
    // Process the response here
  }
};
xhr.send();

Using fetch():

fetch("https://api.example.com/data")
  .then(function (response) {
    if (response.ok) {
      return response.json();
    }
    throw new Error("HTTP status code: " + response.status);
  })
  .then(function (data) {
    // Process the data here
  })
  .catch(function (error) {
    // Handle any errors here
    console.log("Request failed:", error.message);
  });

In both examples, we’re making a GET request to “https://api.example.com/data”. Adjust the URL and HTTP method (GET, POST, etc.) according to your needs. The response is processed in the callback function, where you can access the response data and handle any errors that may occur.

It’s worth noting that the fetch() function provides a more modern and flexible approach for making HTTP requests, but the XMLHttpRequest object is still widely supported in older browsers.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

5 things to know before the stock market opens Friday

5 things to know before the stock market opens Friday Here area unit the foremost…

How To Add Login Authentication to React Applications

How To Add Login Authentication to React Applications To add login authentication to a React…

How to easily unsubscribe from marketing emails right in Gmail

We’ve all been there. Emails are stacking up, and none of them appear necessary within…