| 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)); |
fetch(...).then(response => {
if (response.status == 200){
// Happy Path
} else {
console.log(response.statusText);
}
});
var dataObj;
fetch(...).then(response => response.text())
.then(data => {
dataObj = id;
console.log(dataObj);
});
var jsonObj;
fetch(...).then(response => response.json())
.then(data => {
jsonObj = data;
console.log(jsonObj)
});
async function getData(){
var jsonObj;
const response = await fetch(...);
const data = await response.json();
jsonObj = data;
console.log(jsonObj);
}