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));
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));
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));