精通 Fetch API 的实际 JavaScript 示例
发布: (2026年1月19日 GMT+8 02:37)
3 min read
原文: Dev.to
Source: Dev.to
如果你认真学习 JavaScript,Fetch API 是实际前端开发的核心技能。所有示例都使用免费的假 API:.
1️⃣ 创建用户(POST 请求)
async function createUser(userData) {
const api_url = 'https://jsonplaceholder.typicode.com/users';
const res = await fetch(api_url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(userData),
});
const data = await res.json();
console.log(data);
}
createUser({
id: crypto.randomUUID(),
name: 'Md Fahim',
email: 'mdfahim@gmail.com',
});
- 实际使用场景: 注册表单、管理员仪表盘以及添加新记录。
- 注意: JSONPlaceholder 并不会持久化数据;它仅模拟响应。
2️⃣ 使用相关数据获取用户 (URLSearchParams)
async function fetchUsersWithPosts() {
const api_url = 'https://jsonplaceholder.typicode.com/users';
const queryParams = { _embed: 'posts' };
const queryString = new URLSearchParams(queryParams).toString();
const res = await fetch(`${api_url}?${queryString}`);
const data = await res.json();
console.log(data);
}
fetchUsersWithPosts();
URLSearchParams 是什么?
它将对象转换为有效的查询字符串,例如 { _embed: 'posts' } → _embed=posts`。
- 实际使用场景: 过滤、分页、排序、嵌入相关资源。
3️⃣ Updating Data (PUT vs PATCH)
PUT (Full Update)
async function putUser(data) {
const res = await fetch('https://jsonplaceholder.typicode.com/users/1', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
console.log(await res.json());
}
PATCH (Partial Update – Recommended)
async function patchUser(data) {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${data.id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
console.log(await res.json());
}
patchUser({ id: 3, name: 'Alex Smith' });
- 实际使用场景: 更新个人资料信息、设置或偏好。
4️⃣ 删除用户 (DELETE)
async function deleteUser(userId) {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`, {
method: 'DELETE',
});
console.log(await res.json()); // {}
}
deleteUser(5);
✅ 空对象 {} 是 DELETE 响应的正常返回。
5️⃣ 使用 new Request() 的可复用请求
async function adminDashboard(request) {
const res = await fetch(request);
const data = await res.json();
console.log(data);
}
/* Create Request */
const addUser = new Request('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Hamza Chy', email: 'hamza@gmail.com' }),
});
adminDashboard(addUser);
/* Update Request */
const updateUser = new Request('https://jsonplaceholder.typicode.com/users/11', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Hamza Chowdhury' }),
});
adminDashboard(updateUser);
/* Delete Request */
const deleteUser11 = new Request('https://jsonplaceholder.typicode.com/users/11', {
method: 'DELETE',
});
adminDashboard(deleteUser11);
为什么使用 new Request()?
- 更清晰的架构
- 可复用的请求对象
- 中间件式模式
- 更适合大型应用
6️⃣ 使用 AbortController 中止请求
let controller; // will hold the AbortController instance
async function downloadFile() {
controller = new AbortController();
const res = await fetch('./download/file.txt', {
signal: controller.signal,
});
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'file.txt';
a.click();
URL.revokeObjectURL(url);
}
function abortDownload() {
controller.abort('User cancelled download');
}
- 实际使用场景: 取消搜索请求、停止文件下载、避免竞争条件。