How do I make an HTTP request in Javascript?

 HTTP request in Javascript

How do I make an HTTP request in Javascript?

There are several ways to make an HTTP request in JavaScript, but some of the most popular methods include using the XMLHttpRequest object, the fetch() function, and using a library such as jQuery or Axios.

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

var xhr = new XMLHttpRequest();

xhr.open("GET", "https://example.com", true);

xhr.onreadystatechange = function() {

    if (xhr.readyState === 4 && xhr.status === 200) {

        console.log(xhr.responseText);

    }

};

xhr.send();

And an example using the fetch() function:

fetch("https://example.com")

  .then(response => response.text())

  .then(data => console.log(data));

For more complex operations, you can use a library such as jQuery or Axios.


$.ajax({

  type: "GET",

  url: "https://example.com",

  success: function(data) {

    console.log(data);

  }

});


Copy code

axios.get("https://example.com").then(response => {

    console.log(response.data);

});

It's important to note that the fetch() method is not supported in older browsers, so you should use a library like axios for backwards compatibility.

No comments:

Post a Comment