How do I make an HTTP request in Javascript?

There are several ways to make an HTTP request in JavaScript, including using the XMLHttpRequest object, the fetch API, and various libraries such as axios, jquery, etc.


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

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


And here is an example using the fetch API:


fetch("https://api.example.com/data")
.then((response) => {
return response.text();
})
.then((data) => {
console.log(data);
});


Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.