Fetch Api
Fetch API
以下是使用 Fetch API 进行基本 CRUD 操作和获取数据的详细示例和步骤。
1. 基本用法
首先,确保你的环境支持 Fetch API,现代浏览器都支持该 API。
2. CRUD 示例代码
假设我们使用 https://jsonplaceholder.typicode.com/posts
作为 RESTful API,以下是 CRUD 操作的示例:
2.1 创建(Create)
const createPost = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log('Created Post:', data);
} catch (error) {
console.error('Error creating post:', error);
}
};
createPost();
2.2 读取(Read)
const fetchPosts = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log('Posts:', data);
} catch (error) {
console.error('Error fetching posts:', error);
}
};
fetchPosts();
2.3 更新(Update)
const updatePost = async (postId) => {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: 'Updated Title',
body: 'Updated Body',
userId: 1,
}),
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log('Updated Post:', data);
} catch (error) {
console.error('Error updating post:', error);
}
};
// 调用更新函数,假设要更新 ID 为 1 的帖子
updatePost(1);
2.4 删除(Delete)
const deletePost = async (postId) => {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`, {
method: 'DELETE',
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
console.log('Deleted Post:', response.status); // 204 No Content
} catch (error) {
console.error('Error deleting post:', error);
}
};
// 调用删除函数,假设要删除 ID 为 1 的帖子
deletePost(1);