To make an HTTP request in Javascript, you can use the XMLHttpRequest object, or you can use the more modern fetch() function. Here is an example of how to use fetch() to make a GET request to retrieve some data from a server:
fetch('http://www.example.com/data.json') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error))
This code sends a GET request to the specified URL to retrieve the data in JSON format. The then() function is called with the response from the server, and it logs the data to the console. The catch() function is called if there is an error, and it logs the error to the console.
Alternatively, you can use the XMLHttpRequest object like this:
const request = new XMLHttpRequest();
request.open('GET', 'http://www.example.com/data.json');
request.responseType = 'json';
request.send();
request.onload = () => {
const data = request.response;
console.log(data);
};
request.onerror = () => {
console.error('An error occurred while making the request.');
};
This code creates a new XMLHttpRequest object, opens a GET request to the specified URL, sets the response type to JSON, and sends the request. The onload function is called when the request completes successfully, and it logs the response data to the console. The onerror function is called if there is an error, and it logs an error message to the console.