fetch return javascript code example
Example 1: 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 2: http request javascript fetch
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
Example 3: fetch api javascript
fetch('https://apiYouWantToFetch.com/players')
.then(response => response.json())
.then(players => console.log(players))
Example 4: fetch suntax
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});
Example 5: fetch get request
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);
});