You can make an HTTP request in JavaScript using the built-in fetch() function or by using the XMLHttpRequest (XHR) object.
Here is an example using fetch():
javascriptfetch('https://example.com/mypage')
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error(error));
This code sends a GET request to https://example.com/mypage and logs the response data to the console. You can also use fetch() it to send POST, PUT, DELETE, and other HTTP requests by passing additional options in the second argument of the function.
Here's an example using XHR:
javascriptconst xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/mypage');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
This code creates a new XHR object, opens a GET request to https://example.com/mypage, sets a callback function to handle the response, sends the request, and logs the response data to the console. You can also use XHR to send POST, PUT, DELETE, and other HTTP requests by changing the first argument to xhr.open().