how to make a get request in javascript

Here are two commonly used ways to make a GET request in JavaScript:

Using XMLHttpRequest (XHR):

index.tsx
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    console.log(this.responseText);
  }
};
xhttp.open("GET", "https://example.com/api", true);
xhttp.send();
235 chars
9 lines

Using Fetch API:

index.tsx
fetch('https://example.com/api')
  .then(response => response.text())
  .then(data => console.log(data))
  .catch(error => console.error(error));
146 chars
5 lines

Both of these methods are used to make asynchronous requests and receive responses from servers. The XMLHttpRequest offers more fine-grained control over the request and the response, whereas the Fetch API offers simpler syntax and automatically handles json responses.

gistlibby LogSnag