JavaScript

How do I make an HTTP request in Javascript?

You can make HTTP requests in JavaScript using the XMLHttpRequest (XHR) object, or the more modern and widely used fetch API.

Here’s an example using XHR:

 
				
					var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
  if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
    console.log(this.responseText);
  }
};
xhr.send();

				
			

And here’s an example using fetch:

				
					fetch('https://api.example.com/data')
  .then(response => response.text())
  .then(data => console.log(data))
  .catch(error => console.error(error));

				
			

Note that both XHR and fetch operate asynchronously, so the code that follows the request will continue to run while the request is being processed.

Leave a Reply

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

Back to top button