There are several ways to make an HTTP request in JavaScript. One way is to use the XMLHttpRequest
object, which is available in all modern browsers.
Here is an example of how to use XMLHttpRequest
to send a GET request to a server and print the response:
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhr.open('GET', 'https://example.com/api/endpoint');
xhr.send();
You can also use the fetch()
function, which is a modern way to make HTTP requests and is supported by all modern browsers.
Here is an example of how to use fetch()
to send a GET request and print the response:
fetch('https://example.com/api/endpoint')
.then(response => response.text())
.then(text => console.log(text))
.catch(error => console.error(error));
You can also use a library like axios, which provides a simple interface for making HTTP requests.
Here is an example of how to use axios to send a GET request and print the response:
axios.get('https://example.com/api/endpoint')
.then(response => console.log(response.data))
.catch(error => console.error(error));