fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data);
});
fetch('https://api.example.com/posts')
.then(response => response.json())
.then(posts => {
console.log(posts);
});
fetch('https://api.example.com/data')
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Request failed!');
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error.message);
});
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'value' })
})
.then(response => response.json())
.then(result => {
console.log(result);
});
const postData = { title: 'New Post', content: 'This is a new post.' };
fetch('https://api.example.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
})
.then(response => response.json())
.then(newPost => {
console.log(newPost);
});
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (response.ok) {
const data = await response.json();
console.log(data);
}
} catch (error) {
console.error(error);
}
}
fetchData();