JavaScript Requests quick reference

hoanganhlam

Lam

Posted on December 21, 2023

JavaScript Requests quick reference

JavaScript Requests Cheat Sheet

XMLHttpRequest

Example

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onload = function() {
  if (xhr.status >= 200 && xhr.status < 300) {
    console.log(JSON.parse(xhr.responseText));
  } else {
    console.error('Request failed!');
  }
};
xhr.send();
Enter fullscreen mode Exit fullscreen mode

Fetch API

Example

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
Enter fullscreen mode Exit fullscreen mode

Axios

Example

axios.get('https://api.example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));
Enter fullscreen mode Exit fullscreen mode

Async/Await

Example

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

fetchData();
Enter fullscreen mode Exit fullscreen mode

More Javascript Cheat Sheet

💖 💪 🙅 🚩
hoanganhlam
Lam

Posted on December 21, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

JavaScript Requests quick reference
cheatsheet JavaScript Requests quick reference

December 21, 2023