To make an HTTP request in JavaScript, you can use the XMLHttpRequest
object or the newer fetch()
API. Here’s an example using XMLHttpRequest
:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.example.com/', true);
xhr.onload = function () {
if (xhr.status === 200) {
// Request succeeded. Do something with the response.
var response = xhr.responseText;
} else {
// Request failed. Do something with the error.
}
};
xhr.send();
And here’s an example using fetch()
:
fetch('http://www.example.com/')
.then(function(response) {
// Request succeeded. Do something with the response.
return response.text();
})
.then(function(responseText) {
// Do something with the response text.
})
.catch(function(error) {
// Request failed. Do something with the error.
});
Both examples make a GET
request to the specified URL. You can replace GET
with other HTTP methods (such as POST
, PUT
, etc.) to make requests using those methods. You can also pass additional options and headers to the open()
and fetch()
methods to customize the request.