How do I make an HTTP request in Javascript?

How do I make an HTTP request in Javascript

To make an HTTP request in JavaScript, you can use the XMLHttpRequest object or the more modern fetch API.


Here’s an example using XMLHttpRequest:

var xhr = new XMLHttpRequest();

xhr.open(“GET”, “https://example.com”, true);

xhr.onreadystatechange = function() {

  if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {

    console.log(xhr.responseText);

  }

};

xhr.send();


And here’s an example using the fetch API:


 fetch(“https://example.com”)

 .then(response => response.text())

 .then(data => console.log(data))

 .catch(error => console.error(error));


Note that in both examples, the response from the server is logged to the console, but you can handle the response data in any way you like.

AI Avenue




Discover more from AI Avenue

Subscribe to get the latest posts to your email.

About Abhishek

Avatar

Check Also

google maps

Navigating the World with Google Maps: An In-Depth Exploration

Unlock the potential of Google Maps for seamless navigation and local insights. Your ultimate travel companion awaits with our comprehensive guide.

Leave a Reply

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

Google Fi eSIM on iPhone 15 & 15 Pro: Quick Setup Guide Google Translate: Breaking Language Barriers How to Invest in Stocks| Best Strategies and Risk Management Methods Gridiron Thrills: Lions Stun Chiefs in NFL Opener Experience the Revolutionary Apple Vision Pro