js fetch catch code example
Example 1: try catch fetch
fetch("/api/foo")
.then( response => {
if (!response.ok) { throw response }
return response.json()
})
.then( json => {
this.props.dispatch(doSomethingWithResult(json))
})
.catch( err => {
err.text().then( errorMessage => {
this.props.dispatch(displayTheError(errorMessage))
})
})
Example 2: javascript fetch api post
fetch('https://example.com/profile', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
'foo': 'bar'
}),
})
.then((res) => res.json())
.then((data) => {
})
.catch((err) => console.log(err));
Example 3: fetch js
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 4: how to use fetch() javascript
fetch('http://api.open-notify.org/astros.json')
.then(function(response) {
return response.json();
})
.then(function(json) {
console.log(json)
});
function fetchBooks() {
return fetch('https://anapioficeandfire.com/api/books')
.then(resp => resp.json())
.then(json => renderBooks(json));
}
function renderBooks(json) {
const main = document.querySelector('main')
json.forEach(book => {
const h2 = document.createElement('h2')
h2.innerHTML = `<h2>${book.name}</h2>`
main.appendChild(h2)
})
}
document.addEventListener('DOMContentLoaded', function() {
fetchBooks()
})
Example 5: fetch catch
fetch(url).then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error('Something went wrong');
}
})
.then((responseJson) => {
})
.catch((error) => {
console.log(error)
});