Skip to content

Instantly share code, notes, and snippets.

@long25vn
Forked from jsdf/Fetch-API-cheat-sheet.md
Created May 25, 2021 13:43
Show Gist options
  • Save long25vn/17d271cb6753563db50b568f2950e495 to your computer and use it in GitHub Desktop.
Save long25vn/17d271cb6753563db50b568f2950e495 to your computer and use it in GitHub Desktop.
Fetch API cheat sheet

fetch api cheat sheet

get JSON

fetch('/things/10', {
  credentials: 'same-origin',
  headers: {
    'accept': 'application/json'
  }
})
  .then(res => {
    if (!res.ok) return Promise.reject(new Error(`HTTP Error ${res.status}`));

    return res.json(); // parse json body
  })
  .then(data => {
    // do stuff with data from parsed json response body
    console.log(data);
  })
  .catch(err => console.error(err));

post JSON

const updatedThing = {id: 10, name: 'Keith'};

fetch('/things/10', {
  method: 'post',
  body: JSON.stringify(updatedThing),
  credentials: 'same-origin',
  headers: {
    'content-type': 'application/json'
    'accept': 'application/json'
  }
})
  .then(res => {
    if (!res.ok) return Promise.reject(new Error(`HTTP Error ${res.status}`));

    return res.json(); // parse json body (if you got one)
  })
  .catch(err => console.error(err));

get HTML

fetch('/things/10', {
  credentials: 'same-origin',
  headers: {
    'accept': 'text/html'
  }
})
  .then(res => {
    if (!res.ok) return Promise.reject(new Error(`HTTP Error ${res.status}`));

    return res.text(); // parse text body
  })
  .then(htmlText => {
    // don't do this unless you trust htmlText :)
    document.querySelector('body').innerHTML = htmlText;
  })
  .catch(err => console.error(err));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment