使用 fetch 发送 DELETE 请求需设置 method: 'DELETE',通常通过 URL 传 ID、显式声明 Content-Type;少数情况可带 JSON body;注意认证(token/Cookie)、CORS、状态码处理(如 204 不可调用 res.json)。

用 fetch 发送 DELETE 请求很简单,关键在于正确设置 method 和(通常需要的)headers,并根据后端要求决定是否携带请求体(如 ID 或 JSON 数据)。
基本 DELETE 请求写法
最常见的情况是通过 URL 路径指定要删除的资源 ID:
- 使用
method: 'DELETE' - 一般不需要
body,因为 ID 已包含在 URL 中 - 建议显式设置
Content-Type(即使没 body,部分服务端仍依赖该头)
示例:
fetch('/api/users/123', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
return res.json();
})
.then(data => console.log('删除成功:', data))
.catch(err => console.error('删除失败:', err));
带 JSON 请求体的 DELETE(少数后端要求)
有些 API 设计会把删除参数放在请求体中(比如批量删除、或需额外验证字段),这时需传 body:
立即学习“Java免费学习笔记(深入)”;
Java开发手册规约集合,基于阿里巴巴Java开发手册(嵩山版)。 涵盖7大维度:编程规约、异常日志、单元测试、安全规约、MySQL数据库、工程结构、设计规约。 当用户需要:(1) 编写或审查Java代码 (2) 检查命名/代码规范 (3) 处理异常和日志 (4) 编写单元测试 (5) 安全编码 (6) 数据库设...
- 用
JSON.stringify()序列化对象 - 确保
Content-Type是'application/json' - 注意:不是所有服务器都支持 DELETE 带 body,先确认接口文档
示例:
fetch('/api/posts', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ ids: [101, 102, 103] })
})
.then(res => res.json())
.then(() => console.log('批量删除成功'));
处理认证和跨域注意事项
实际项目中常需携带凭证或 token:
- 用
credentials: 'include'发送 Cookie(如登录态) - 手动添加
Authorization头(如 Bearer Token) - 确保后端已配置 CORS,允许
DELETE方法及对应 headers
示例(带 token):
const token = 'eyJhbGciOiJIUzI1NiIs...';
fetch('/api/comments/456', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
});
错误处理与状态判断建议
DELETE 成功不等于返回 200 —— 常见成功状态码包括 200、202(已接受)、204(无响应体)。务必检查 res.ok 或 res.status:
-
res.ok为true表示状态码在 200–299 范围 - 若后端返回
204 No Content,调用res.json()会报错,应改用res.text()或直接忽略 body - 网络错误(如离线、域名不可达)会进入
catch;HTTP 错误(如 404、500)需在then中手动判断
更稳妥的处理方式:
fetch('/api/items/789', { method: 'DELETE' })
.then(res => {
if (res.status === 204) {
console.log('删除成功,无返回内容');
return;
}
if (!res.ok) throw new Error(`删除失败: ${res.status}`);
return res.json();
})
.then(data => console.log('响应数据:', data))
.catch(err => console.error('请求异常:', err));

















