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.

Free website review

Three things we would fix on your site, in writing, within a week

We have built and looked after websites for Sydney businesses since 2016, and the first thing we do with any new client is exactly this: look properly and say what we see. Send us the address and we will do the same for you. No sales sequence, no automated follow up, one honest reply.

"*" indicates required fields

This field is for validation purposes and should be left unchanged.

One working day to acknowledge, up to a week for the review. Your details stay with the Defyn team in Sydney.

Insights

The latest from our knowledge base

WordPress.com Pro Partner WooCommerce Pro Partner Shopify Certified
Free website review