To make an HTTP GET request in JavaScript, you can use the XMLHttpRequest object or the fetch() function.
Here's an example of making an HTTP GET request using XMLHttpRequest:
function makeGetRequest(url) {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.open('GET', url);
xhr.send();
}
makeGetRequest('https://www.example.com');
Here's an example of making an HTTP GET request using fetch():
fetch('https://www.example.com')
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error(error));
Note that both XMLHttpRequest and fetch() are asynchronous, which means that the code will not wait for the response to complete before continuing to execute. Instead, they provide a way to specify a callback function that will be called when the response is received.
Top comments (0)