3、Fetch进阶:POST请求、PUT与DELETE、请求头设置、错误处理
上一节我们聊了怎么用 Fetch 拿数据。但真实项目里,光会 GET 可不够。你想想看,用户注册、提交表单、更新资料、删除记录……这些操作背后都是 POST、PUT、DELETE 在干活。
这一节,我们就来把这些「写操作」彻底搞明白。我会把我在项目中踩过的坑、总结的技巧,一股脑儿倒给你。
3.1 POST 请求:向服务器发送数据
POST 请求说白了就是「往服务器塞数据」。最常见的场景就是用户登录或注册。
先看一个最基础的 POST 示例:
const loginUser = async (email, password) => {
try {
const response = await fetch('https://api.example.com/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
password: password,
}),
});
const data = await response.json();
console.log('登录成功:', data);
return data;
} catch (error) {
console.error('登录失败:', error);
throw error;
}
};
这里有几个关键点,我当初刚学时也迷糊过:
- method: 'POST' —— 告诉 Fetch 这是 POST 请求,不是默认的 GET
- headers 里的 Content-Type —— 声明你发送的数据格式。JSON 数据就用
application/json - body 需要序列化 —— 不能直接传 JavaScript 对象,得用
JSON.stringify()转成字符串
3.2 PUT 与 DELETE:更新和删除操作
PUT 和 DELETE 的写法跟 POST 几乎一样,只是 method 不同。但它们的语义和使用场景差别很大。
PUT 请求:更新资源
PUT 一般用于「全量更新」某个资源。比如修改用户资料:
const updateUserProfile = async (userId, profileData) => {
try {
const response = await fetch(`https://api.example.com/users/${userId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your_token_here',
},
body: JSON.stringify(profileData),
});
if (!response.ok) {
throw new Error(`更新失败: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('更新用户资料出错:', error);
throw error;
}
};
DELETE 请求:删除资源
DELETE 请求一般不需要 body,只需要告诉服务器你要删哪个资源:
const deletePost = async (postId) => {
try {
const response = await fetch(`https://api.example.com/posts/${postId}`, {
method: 'DELETE',
headers: {
'Authorization': 'Bearer your_token_here',
},
});
if (response.status === 204) {
console.log('删除成功,无返回内容');
return true;
}
if (!response.ok) {
throw new Error(`删除失败: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('删除操作出错:', error);
throw error;
}
};
你可能会问:为什么 DELETE 请求有时返回 204?204 的意思是「服务器已处理,但没有内容返回」。很多 API 设计者认为删除操作不需要返回数据,所以直接返回 204。我个人觉得这样挺合理的,省了一次 JSON 解析。
3.3 请求头设置:不只是 Content-Type
实际项目中,请求头里要放的东西可多了。除了 Content-Type,最常见的还有:
| 请求头 | 用途 | 示例值 |
|---|---|---|
| Authorization | 身份认证 | Bearer eyJhbGciOiJIUzI1NiIs... |
| Accept | 告诉服务器你期望的响应格式 | application/json |
| X-Requested-With | 标识 AJAX 请求(防 CSRF) | XMLHttpRequest |
| Cache-Control | 控制缓存行为 | no-cache |
来看一个带多个请求头的完整示例:
const apiRequest = async (url, options = {}) => {
const defaultHeaders = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
};
// 合并自定义请求头
const headers = {
...defaultHeaders,
...options.headers,
};
// 如果有 token,自动带上
const token = await getStoredToken();
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
const response = await fetch(url, {
...options,
headers,
});
return response;
};
3.4 错误处理:别让用户看到白屏
错误处理是 API 集成里最容易忽视、也最容易出问题的地方。很多新手只写 try-catch,但 catch 到的错误类型其实很复杂。
网络错误 vs HTTP 错误
这两者完全不是一回事:
- 网络错误:断网、DNS 解析失败、请求超时 —— 这些会触发 catch
- HTTP 错误:404、500、401 —— 这些不会触发 catch,因为请求本身成功了
为什么会这样?因为 Fetch 只有在网络层面出问题时才会 reject。服务器返回 500,对 Fetch 来说依然是「成功的响应」。
所以正确的做法是:
const fetchWithErrorHandling = async (url, options = {}) => {
try {
const response = await fetch(url, options);
// 手动检查 HTTP 状态码
if (!response.ok) {
// 尝试解析错误信息
let errorMessage = `HTTP 错误: ${response.status}`;
try {
const errorData = await response.json();
errorMessage = errorData.message || errorMessage;
} catch (e) {
// 如果错误响应不是 JSON,就用默认信息
}
throw new Error(errorMessage);
}
return await response.json();
} catch (error) {
// 这里可能是网络错误,也可能是我们手动抛出的 HTTP 错误
if (error.message.includes('Network request failed')) {
console.error('网络连接失败,请检查网络');
// 可以在这里触发重试逻辑
} else if (error.message.includes('HTTP 错误')) {
console.error('服务器返回错误:', error.message);
} else {
console.error('未知错误:', error);
}
throw error;
}
};
超时处理
Fetch 默认没有超时机制。如果服务器一直不响应,请求会挂在那里。我的做法是用 AbortController 来实现超时:
const fetchWithTimeout = (url, options = {}, timeout = 10000) => {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
return fetch(url, {
...options,
signal: controller.signal,
})
.then(response => {
clearTimeout(timeoutId);
return response;
})
.catch(error => {
clearTimeout(timeoutId);
if (error.name === 'AbortError') {
throw new Error('请求超时');
}
throw error;
});
};
超时时间设多少合适?我个人习惯是 10 秒。太短了容易误判,太长了用户等不起。你可以根据自己项目的接口响应速度来调整。
3.5 实战:封装一个通用的请求工具
把上面这些知识点串起来,我们可以封装一个比较完整的请求工具:
class ApiClient {
constructor(baseURL, defaultHeaders = {}) {
this.baseURL = baseURL;
this.defaultHeaders = {
'Content-Type': 'application/json',
...defaultHeaders,
};
}
async request(endpoint, options = {}) {
const url = `${this.baseURL}${endpoint}`;
const headers = {
...this.defaultHeaders,
...options.headers,
};
// 自动添加 token
const token = await this.getToken();
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000);
try {
const response = await fetch(url, {
...options,
headers,
signal: controller.signal,
});
clearTimeout(timeoutId);
if (!response.ok) {
const error = new Error(`请求失败: ${response.status}`);
error.status = response.status;
throw error;
}
// 204 No Content 不需要解析
if (response.status === 204) {
return null;
}
return await response.json();
} catch (error) {
clearTimeout(timeoutId);
if (error.name === 'AbortError') {
throw new Error('请求超时,请稍后重试');
}
throw error;
}
}
get(endpoint, params = {}) {
const queryString = Object.entries(params)
.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
.join('&');
const url = queryString ? `${endpoint}?${queryString}` : endpoint;
return this.request(url, { method: 'GET' });
}
post(endpoint, data) {
return this.request(endpoint, {
method: 'POST',
body: JSON.stringify(data),
});
}
put(endpoint, data) {
return this.request(endpoint, {
method: 'PUT',
body: JSON.stringify(data),
});
}
delete(endpoint) {
return this.request(endpoint, { method: 'DELETE' });
}
async getToken() {
// 从安全存储中获取 token
// 具体实现取决于你用的存储方案
return null;
}
}
// 使用示例
const api = new ApiClient('https://api.example.com/v1');
// GET 请求
api.get('/users', { page: 1, limit: 20 })
.then(data => console.log(data))
.catch(error => console.error(error));
// POST 请求
api.post('/users', { name: '张三', email: 'zhangsan@example.com' })
.then(data => console.log('创建成功:', data))
.catch(error => console.error('创建失败:', error));
// PUT 请求
api.put('/users/123', { name: '李四' })
.then(data => console.log('更新成功:', data))
.catch(error => console.error('更新失败:', error));
// DELETE 请求
api.delete('/users/123')
.then(() => console.log('删除成功'))
.catch(error => console.error('删除失败:', error));
这个封装看起来代码不少,但用起来特别顺手。你想想看,每个请求都不用重复写 headers、超时、错误处理,多省事。
好了,这一节的内容就到这里。POST、PUT、DELETE 的写法其实大同小异,关键是理解它们的语义和适用场景。再加上完善的错误处理,你的 API 集成就能稳如老狗了。
下一节,我们会聊聊更高级的话题:请求拦截、响应拦截、请求重试和离线队列。这些东西在实际项目中非常实用,到时候见。