Skip to content

Instantly share code, notes, and snippets.

@jsdf
Last active August 18, 2022 20:23
Show Gist options
  • Save jsdf/ac769acdd3882f582e283b166d6c0293 to your computer and use it in GitHub Desktop.
Save jsdf/ac769acdd3882f582e283b166d6c0293 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