js fetch api json code example
Example 1: js fetch 'post' json
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 2: fetch api javascript
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 3: .fetch method
fetch('http://example.com/data.json')
.then(data => data);
.catch(err => console.log(err));