Make HTTP Request in Javascript (with sample code)

You can make an HTTP request in JavaScript using the XMLHttpRequest object or the fetch API. However, other methods are also available such as jQuery Ajax and etc. In this post, I will show you how to make HTTP requests in Javascript using two of the fastest methods available along with the sample code for easy understanding.

XMLHttpRequest object

Here’s an example using the XMLHttpRequest object:

JavaScript
const request = new XMLHttpRequest();
request.open('GET', 'https://example.com/api/data');
request.send();

request.onreadystatechange = function() {
  if (this.readyState === 4 && this.status === 200) {
    const response = JSON.parse(this.responseText);
    console.log(response);
  }
};

In this example, a GET request is sent to https://example.com/api/data using the XMLHttpRequest object. When the readystatechange event is fired, the code checks if the request has been completed (readyState === 4) and if the status code is 200 (status === 200). If both conditions are true, the response is parsed as JSON and logged to the console.

fetch API

Here is an example using the fetch API:

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

In this example, a GET request is sent to https://example.com/api/data using the fetch API. The response is then parsed as JSON and logged to the console. If an error occurs, it is logged into the console as well.

Note that the fetch API returns a Promise, which allows you to chain multiple asynchronous operations together.

Leave a Reply

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

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top