How do I make an HTTP request in Javascript?
There are several ways to make an HTTP request in JavaScript, but the most common way is to use the XMLHttpRequest
object, which is built into most web browsers. Here's an example of how you might use it to send a GET request to an endpoint:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.example.com');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
In this example, xhr.open
is used to open a GET request to the specified URL. The onreadystatechange
event is used to check the status of the request, and when the request is complete, the response text is logged to the console. The xhr.send()
method is used to actually send the request.
You can also use the fetch
function to make http requests .
fetch('https://www.example.com')
.then(response => response.text())
.then(data => console.log(data))
And also you can use a library like axios,superagent, isomorphic-fetch, etc
import axios from 'axios';
axios.get('https://www.example.com')
.then(response => console.log(response.data))
You can also use the await
/async
syntax to make the request:
const getData = async() => {
const response = await axios.get('https://www.example.com')
console.log(response.data);
}
getData()
Please note that, you might need to add some headers and pass data while sending the request in many cases, above example just demostrate the basic request.