JavaScript Requests Cheat Sheet

1. Using `XMLHttpRequest` (Old way)

Basic GET Request

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(xhr.responseText); // Response data
  }
};
xhr.send();

Basic POST Request

const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/data', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(xhr.responseText); // Response data
  }
};
xhr.send(JSON.stringify({ name: 'Alice', age: 25 }));

2. Using `Fetch API` (Modern way)

Basic GET Request

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

Basic POST Request

fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ name: 'Alice', age: 25 }),
})
  .then(response => response.json())
  .then(data => console.log(data))  // Response data
  .catch(error => console.error('Error:', error));

3. Handling JSON Responses

Using `Fetch`

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) throw new Error('Network response was not ok');
    return response.json(); // Parsing JSON
  })
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

4. Handling Errors

With `XMLHttpRequest`

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onerror = function() {
  console.error('Request failed');
};
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      console.log(xhr.responseText); // Success
    } else {
      console.error('Error:', xhr.statusText);
    }
  }
};
xhr.send();

With `Fetch`

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .catch(error => console.error('Fetch error:', error));

5. Adding Query Parameters

With `Fetch`

const params = new URLSearchParams({ userId: 1, postId: 2 });
fetch(`https://api.example.com/data?${params}`)
  .then(response => response.json())
  .then(data => console.log(data));

6. Using `async`/`await` (for `Fetch`)

Basic Example

async function getData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) throw new Error('Network response was not ok');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}
getData();

7. Sending Headers

With `Fetch`

fetch('https://api.example.com/data', {
  method: 'GET',
  headers: {
    'Authorization': 'Bearer your_token',
    'Content-Type': 'application/json'
  }
})
  .then(response => response.json())
  .then(data => console.log(data));