In JavaScript, you can make an HTTP request using the XMLHttpRequest
object or the newer fetch
API. Here's how to use both methods:
Using XMLHttpRequest:
javascriptconst xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.onload = () => {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error('Error!', xhr.statusText);
}
};
xhr.send();
In the example above, we create a new XMLHttpRequest object and open a GET request to https://example.com/api/data
. We then define an onload
callback function that will be executed when the response is received. If the response status is 200 (OK), we log the response text to the console. Otherwise, we log an error message.
Using fetch:
javascriptfetch('https://example.com/api/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error!', error));
In the example above, we use the fetch API to send a GET request to https://example.com/api/data
. We then chain two .then()
functions to parse the response as JSON and log the resulting data to the console. Finally, we add a .catch()
function to log any errors that may occur during the request.