Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

To make an HTTP request in JavaScript, you can use the built-in fetch function or create an

XMLHttpRequest object. Here's an example of using both methods:

Using fetch:

javascript
Copy code
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// Process the response data
console.log(data);
})
.catch(error => {
// Handle any errors
console.error('Error:', error);
});
Using XMLHttpRequest:

javascript
Copy code
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onload = function() {
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
// Process the response data
console.log(data);
} else {
// Handle the error
console.error('Request failed. Status:', xhr.status);
}
};
xhr.onerror = function() {
// Handle any network errors
console.error('Network error');
};
xhr.send();
Both methods allow you to make HTTP requests, but fetch is a newer and more modern
approach, providing a more straightforward and streamlined API. However, XMLHttpRequest is
still widely supported in older browsers.
Note: In both examples, the HTTP request is a GET request to the URL
'https://api.example.com/data'. You can modify the URL and request method (GET, POST, PUT,
DELETE, etc.) based on your specific needs.

You might also like