async function yourFunction() { //Most compact way to return a fetch
const response = await fetch('some-url', {});
const json = await response.json();
return json; //do here wathever with your json if you want to return
} //a specific part of it.
yourFunction().then(resp => {
console.log(resp); //Here you get the function response and print it
});
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});
// Update fields in form based on API GET request
function update_form_fields(term, field){
fetch("/api/profiles/?format=json")
.then((response)=>{
return response.json();
}).then((data) => {
let profile = data.find(el => el[field] == term);
document.getElementById("name-input").value = profile.name;
document.getElementById("email-input").value = profile.email;
});}
//feth method
// - take the url as parameter
// - return a promise
// - pass response when resolved
// - pass error when rejected
// - the response has the http response information
// - use the .json() is used to get the body of the response
// - .json return a promise
// - resolve the promise with data as the argument
fetch("test.json")
.then(response =>{
return response.json();
}).then(data=>{
document.body.innerHTML = data.name;
console.log(data)
}).catch(error =>{
console.error(error)
})