How do I make an HTTP request in Javascript?
To make an HTTP request in JavaScript, you can use the XMLHttpRequest object or the fetch() function. Here is an example of how to use XMLHttpRequest to make a GET request to fetch a JSON object:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://example.com/api/endpoint", true);
xhr.onload = function () {
var data = JSON.parse(this.responseText);
// do something with the data
};
xhr.send();
Here is an example of how to use fetch() to make a GET request to fetch a JSON object:
fetch("https://example.com/api/endpoint")
.then(response => response.json())
.then(data => {
// do something with the data
});
Both XMLHttpRequest and fetch() are asynchronous, which means that the code will not wait for the response to come back before continuing to execute. Instead, the onload event handler or the then() callback function is called when the response is received. This allows you to perform other tasks in your script while the request is being processed.


0 Comments