To make an HTTP request in JavaScript, you can use the built-in XMLHttpRequest
object or the newer fetch()
API. Here's how you can use both:
Using XMLHttpRequest:
javascriptconst xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
Using fetch():
javascriptfetch('https://example.com/api/data')
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error(error));
Both examples above make a GET request to https://example.com/api/data
. Once the response is received, the first example logs the response as text to the console, while the second example logs the response data as text to the console using Promises.
Note that the fetch()
method returns a Promise, which you can use to handle the response asynchronously.
No comments:
Post a Comment