DEV Community

Lam
Lam

Posted on

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

Top comments (0)