POST JSON 提交与状态码检查 | 星雨笔录
发送 JSON 请求体并正确判断 HTTP 响应。
核心: POST JSON 时设置 Content-Type、用 JSON.stringify 生成请求体,并检查响应状态码。
最小示例:
const res = await fetch('/api/items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: '新文章' })
});
if (!res.ok) throw new Error(res.status);
学完能做: 发送 JSON 请求体并正确判断 HTTP 响应。