Skip to Content
16 January, 2023

How do i make an HTTP request in javascript

Table of Content

There are several ways to make an HTTP request in JavaScript, such as using the XMLHttpRequest object, the fetch() API, or a library like axios or jQuery.

Here is an example of making a GET request using the XMLHttpRequest object:

Copy codevar xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var data = JSON.parse(xhr.responseText);
        console.log(data);
    }
};
xhr.send();

And here is an example of making a GET request using the fetch() API:

Copy codefetch("https://api.example.com/data")
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    console.log(data);
  });

You can use any library as well like axios or jquery ajax etc.

axios.get('https://api.example.com/data')
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });
Copy code
$.ajax({
  url: 'https://api.example.com/data',
  type: 'GET',
  success: function(data) {
    console.log(data);
  }
});

There are many other ways as well to make http request in javascript like using async/await etc.

Insights

The latest from our knowledge base