You are on page 1of 2

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 both approaches:

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 responseData = JSON.parse(xhr.responseText);

// Process the response data

};

xhr.onerror = function() {

// Handle error

};

xhr.send();

Using fetch:

javascript

Copy code

fetch('https://api.example.com/data')

.then(function(response) {

if (response.ok) {
return response.json();

throw new Error('Network response was not OK');

})

.then(function(data) {

// Process the response data

})

.catch(function(error) {

// Handle error

});

Both methods support various HTTP methods such as GET, POST, PUT, DELETE, etc. You can also add
headers and send data with the request if needed.

You might also like