Skip to content

Instantly share code, notes, and snippets.

@SoftwareDevPro
Created November 21, 2020 01:09
Show Gist options
  • Select an option

  • Save SoftwareDevPro/b005363e0a52f6035152d1647ce79574 to your computer and use it in GitHub Desktop.

Select an option

Save SoftwareDevPro/b005363e0a52f6035152d1647ce79574 to your computer and use it in GitHub Desktop.
Common Fetch API requests,and response handling

Fetch Cheatsheet

The most common API requests

Type Example
1. Simple GET request fetch('{url}').
  then(response => console.log(response));
2. Simple POST request fetch('{url}', { method: 'post' })
  .then(response => console.log(response));
3. GET with an authorization token (Bearer) fetch('{url}', { headers: { 'Authorization': 'Basic {token}' } })
  .then(response => console.log(response));
4. GET with querystring data fetch('{url}?var1=value1&var2=value2').
  then(response => console.log(response));
5. GET with CORS fetch('{url}', { mode: 'cors' }).
  then(response => console.log(response));
6. POST with authorization token and querystring data fetch('{url}?var1=value1&var2=value2',
{
  method: 'post', headers: { 'Authorization': 'Bearer {token}' }
})
.then(response => console.log(response));
7. POST with form data let formData = new FormData();
formData.append('field1', 'value1');
formData.append('field2', 'value2');

fetch('{url}', {
  method: 'post',  body: formData
}).then(response => console.log(response));
8. POST with JSON data fetch('{url}', {
  method: 'post',
  headers: {
      'Content-Type': 'application/json'
    },
  body: JSON.stringify({
      'field1': 'value1',
      'field2': 'value2'
  })
}).then(response => console.log(response));
9. POST with JSON data and CORS fetch('{url}', {
  method: 'post',
  mode: 'cors',
  headers: {
   'Content-Type': 'application/json'
  },
  body: JSON.stringify({
   'field1': 'value1',
   'field2': 'value2'
  })
}).then(response => console.log(response));

How to check the status code of response

fetch(...).then(response => {
  if (response.status == 200){
    // Happy Path
  } else {
    console.log(response.statusText);
  }
});

How to get a simple value from the response

var dataObj;

fetch(...).then(response => response.text())
          .then(data => {
   dataObj = id;
   console.log(dataObj);
});

How to convert response to JSON

var jsonObj;

fetch(...).then(response => response.json())
          .then(data => {
    jsonObj = data;
    console.log(jsonObj)
});

Using the async/await method


async function getData(){
    var jsonObj;

    const response = await fetch(...);
    const data = await response.json();
    jsonObj = data;
    console.log(jsonObj);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment