fetch response json or text code example
Example 1: js fetch api
async function postData(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify(data)
});
return response.json();
}
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data);
});
Example 2: fetch response json or text
const _fetch = async props => {
const { endpoint, options } = props
return await fetch(endpoint, options)
.then(async res => {
if (res.ok) {
return await res.clone().json().catch(() => res.text())
}
return false
})
.catch(err => {
console.error("api", "_fetch", "err", err)
return false
})
}