make get request in javascript

Here are four ways to make a GET request in JavaScript:

1. Using XMLHttpRequest (XHR)

index.tsx
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true);
xhr.onload = () => {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.log('Error Occurred');
  }
}
xhr.send();
251 chars
11 lines

2. Using Fetch API

index.tsx
fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
165 chars
5 lines

3. Using jQuery

index.tsx
$.get('https://jsonplaceholder.typicode.com/posts', (data) => console.log(data))
81 chars
2 lines

4. Using Axios

index.tsx
axios.get('https://jsonplaceholder.typicode.com/posts')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
145 chars
4 lines

gistlibby LogSnag