How Do I Make An HTTP Request In Javascript?

To make an HTTP request in JavaScript, you can use the XMLHttpRequest object, or you can use the fetch() function.

Here's an example of how to make an HTTP GET request using XMLHttpRequest:

How Do I Make An HTTP Request In Javascript?
Mannu Rani
Dec 29, 2022
Development

var xhr = new XMLHttpRequest();

xhr.open('GET', 'http://www.example.com/api/data');

xhr.send();

xhr.onreadystatechange = function() {

if (xhr.readyState == XMLHttpRequest.DONE) {

console.log(xhr.responseText);

}

}

And here's an example of how to make an HTTP GET request using fetch():

fetch('http://www.example.com/api/data')

.then(function(response) {

return response.text();

})

.then(function(text) {

console.log(text);

});

Note that fetch() is promise-based, so you need to use then() to access the response.

You can also use fetch() to make other types of HTTP requests, such as POST, PUT, and DELETE. To do this, you can pass an additional options object as the second argument to fetch(), like this:

fetch('http://www.example.com/api/data', {

method: 'POST',

body: JSON.stringify({

name: 'John',

age: 30

}),

headers: {

'Content-Type': 'application/json'

}

})

.then(function(response) {

return response.text();

})

.then(function(text) {

console.log(text);

});

I hope this helps! Let me know if you have any questions.