How do I make an HTTP request in Javascript?
--
There are several ways to make an HTTP request in JavaScript, but the most common and widely-used method is the XMLHttpRequest
object, which is supported by all modern browsers.
Here is an example of how to make a GET request using the XMLHttpRequest
object:
var xhr = new XMLHttpRequest();
xhr.open(‘GET’, ‘https://example.com', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
Another popular way to make HTTP requests in JavaScript is using a library such as fetch
or axios
.
fetch(‘https://example.com')
.then(response => response.json())
.then(data => {
console.log(data);
});
axios.get(‘https://example.com')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
You can also use async-await
with fetch
or axios
async function getData() {
const response = await fetch(‘https://example.com');
const data = await response.json();
console.log(data);
}
getData();
async function getData() {
try {
const response = await axios.get(‘https://example.com');
console.log(response.data);
} catch (error) {
console.error(error);
}
}
getData();
Keep in mind that the above examples are for GET requests, for a POST request you need to change the first argument of the ‘open’ method to ‘POST’ and also set the request header and body accordingly.