用 fetch 发起 JSON POST 请求需设 headers 为 'Content-Type': 'application/json' 并用 JSON.stringify() 转对象为字符串作 body;须检查 response.ok 处理 HTTP 错误,且 headers 键名大小写不敏感但值严格匹配。

用 fetch 发起带 JSON 数据的 POST 请求,关键在于两件事:设置正确的请求头(Content-Type: application/json),并把 JavaScript 对象用 JSON.stringify() 转成字符串再传给 body。
基础写法:发送简单 JSON 对象
这是最常见场景,比如提交表单数据或调用后端 API:
fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: 'alice',
password: '123456'
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error('请求失败:', err));
注意 headers 和 body 的配合
Content-Type 必须显式声明为 application/json,否则后端可能无法正确解析;body 只接受字符串、Blob、FormData 等类型,不能直接传对象 —— 忘记 JSON.stringify() 是最常见的错误。
- ✅ 正确:
body: JSON.stringify({x: 1}) - ❌ 错误:
body: {x: 1}(会转成[object Object]) - ❌ 错误:
headers缺失或写成'content-type'(大小写敏感,建议小写 key 但值严格匹配)
进阶:携带认证 token 或其他 header
很多接口需要身份凭证,可一并在 headers 中添加:
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
fetch('/api/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
title: 'Hello World',
content: 'First post'
})
});
处理响应和错误的实用建议
fetch 不会在 HTTP 状态码出错(如 400、500)时自动 reject,需手动检查 response.ok 或 response.status:
fetch('/api/submit', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(result => console.log('成功:', result))
.catch(err => console.error('失败:', err.message));


















