/ Gists / Ajax / Fetch()
On gists

Ajax / Fetch()

JavaScript

examples.js Raw #

/**
 * Fetch
 * 
 * RESTFul API - https://jsonplaceholder.typicode.com/
 * Docs - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
 */

fetch('https://jsonplaceholder.typicode.com/comments/1')
    .then(response => response.json())
    .then(data => console.log(data))

fetch('https://jsonplaceholder.typicode.com/comments', {
        method: "POST",
        body: JSON.stringify({
            postId: 1,
            name: 'Dylan',
            email: 'dylansemail310@gmail.com',
            body: 'That was dope!'
        })
    })
    .then(response => response.json())
    .then(data => console.log(data))
    
    
    
    /*
    examples
    */
    
  fetch('https://api.example.com/items')
  .then(res => res.json())
  .then(data => {
    console.log(data) 
  })
  .catch(err => {
    console.log('Error:', err)
  })
  

// POST  
const body = {title: 'Foo', body: 'Bar'};

fetch('https://api.example.com/items', {
  method: 'POST', 
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(body)
})
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.log(err))
  
  
  
// FILE UPLOAD
const formData = new FormData();
formData.append('file', fileInput.files[0]);

fetch('https://api.example.com/upload', {
  method: 'POST',
  body: formData
});


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

fetchData();


// Fetching From Multiple Sources
async function get() {

  const [userRes, postsRes] = await Promise.all([
    fetch('/user'),
    fetch('/posts')
  ]);
  
  const user = await userRes.json();
  const posts = await postsRes.json();

  return {user, posts};

}

const data = await get();


// ERRORS
fetch('https://api.example.com/items')
  .then(res => {
    // Handle response
  })
  .catch(err => {
    console.log('Fetch Error :-S', err);  
  });
  
  
  fetch('https://api.example.com/items')
  .then(res => {
    if (!res.ok) {
      throw new Error('Bad status code'); 
    }
   
    return res.json()
  })
  .then(data => {
    console.log(data); 
  })
  .catch(err => {
    console.log('Error:', err); 
  });
  
  
  
  
  // full config with cors and auth

  fetch('https://api.example.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token123'
  },
  body: JSON.stringify({ name: 'Alice', age: 25 }),
  mode: 'cors',
  cache: 'no-cache',
  credentials: 'same-origin'
});





//  Built-In Request Abortion Mechanism
const controller = new AbortController();
const signal = controller.signal;

fetch('https://api.example.com/data', { signal })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => {
    if (error.name === 'AbortError') {
      console.log('Request was cancelled');
    } else {
      console.error('Request failed:', error);
    }
  });
// Cancel the request after 3 seconds
setTimeout(() => controller.abort(), 3000);





// Improved Error Handling
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));