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



Previous Article

Natural language processing (NLP) and computer vision

Next Article

Artificial Intelligence basics and definition

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