Technology

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



About the author

Avatar

Abhishek

Add Comment

Click here to post a comment

Web Stories

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Google Core Update August 2024 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 Experience the Revolutionary Apple Vision Pro