To make an HTTP request in JavaScript, you can use the XMLHttpRequest object or the newer fetch
API. Here's an example of both methods:
Using XMLHttpRequest:
javascript
Copy code
var xhr = new XMLHttpRequest(); xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200)
{ var response = JSON.parse(xhr.responseText); // Process the response data here } };
xhr.send();
In this example, we create a new XMLHttpRequest object, open a GET request to the specified URL
(https://api.example.com/data), and set the onreadystatechange event handler to handle the
response. When the ready state changes to 4 (indicating that the response has been received) and
the status is 200 (indicating a successful response), we can process the response.
Using fetch API:
javascript
Copy code
fetch("https://api.example.com/data") .then(function(response) { if (response.ok) {
return response.json(); } else { throw new Error("Error: " + response.status); } })
.then(function(data) { // Process the response data here }) .catch(function(error) {
console.log(error); });
With the fetch API, we directly call the fetch function with the URL. It returns a Promise that resolves
to the Response object. We can then use the ok property of the response to check if the request was
successful. If so, we can call the json() method on the response to parse the response data. Finally,
we can process the data in the second .then() block or handle any errors in the .catch() block.
Both methods can be used to make different types of requests (GET, POST, etc.), and you can set
request headers, send data in the request body, and handle other aspects of the HTTP
request/response cycle.