
07/03/2023
To make an HTTP request in JavaScript, you can use the built-in XMLHttpRequest object or the newer fetch API. Here's an example of how to make a simple GET request using both methods:
Using XMLHttpRequest:
javascript
Copy code
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.onload = function() {
if (xhr.status === 200) {
const responseData = JSON.parse(xhr.responseText);
console.log(responseData);
} else {
console.log('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
Using fetch:
javascript
Copy code
fetch('https://example.com/api/data')
.then(response => {
if (!response.ok) {
throw new Error('Request failed');
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});
Note that in both cases, we're making a GET request to https://example.com/api/data and logging the response data to the console. You can modify the request method, URL, headers, and body to suit your needs.