what is Fetch code example
Example 1: javascript fetch api
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});
Example 2: 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 3: fetch
fetch(`https://api.example.com/comments`, {
method: 'POST',
headers: {
'Authorization': 'Basic SGVsbG8gdGhlcmUgOikgSGF2ZSBhIGdvb2QgZGF5IQ==',
'Content-Type': 'application/json',
},
body: JSON.stringify({
UID: 58,
Comment: "Fetch is really easy!",
}),
})
.then((response) => response.json())
.then((newComment) => {
});
Example 4: fetch api javascript
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((myJson) => {
console.log(myJson);
});
Example 5: fetch
const data = { username: 'example' };
fetch('https://example.com/profile', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((data) => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
Example 6: .fetch method
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));