用 fetch 发送 json 请求需三步:设置 method 为 post、添加 "content-type": "application/json" 头、用 json.stringify() 序列化数据;推荐 async/await 写法并检查 response.ok。
☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 多模态理解力帮你轻松跨越从0到1的创作门槛☜☜☜

Kim 发送 Jev JSON 请求,其实是指用 JavaScript(常被误写为 “Jev”)向服务器发送 JSON 格式的数据,通常通过 fetch 或 XMLHttpRequest。下面给一个**开箱即用、复制粘贴就能跑**的现代写法(基于 fetch),适用于浏览器或 Node.js(需搭配 node-fetch)。
✅ 正确写法:用 fetch 发送 JSON 请求(推荐)
这是最常用、最简洁的方式,自动设置 Content-Type: application/json,并正确序列化数据:
const data = { name: "Kim", age: 28, city: "Seoul" };
fetch("https://httpbin.org/post", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(json => console.log("响应:", json))
.catch(err => console.error("请求失败:", err));
? 小贴士:
-
必须调用
JSON.stringify()—— 直接传对象会报错 -
必须显式设置
"Content-Type": "application/json"—— 否则后端可能无法识别 -
https://httpbin.org/post是免费测试接口,返回你发的原始数据,适合验证
? 如果要用 async/await(更清晰)
等价写法,更易读、便于错误处理:
async function sendJson() {
const data = { user: "Kim", action: "login", token: "abc123" };
try {
const res = await fetch("https://httpbin.org/post", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
const result = await res.json();
console.log("成功收到:", result.json);
} catch (err) {
console.error("出错了:", err);
}
}
sendJson(); // 直接调用
⚠️ 常见错误(别踩坑)
-
漏写
JSON.stringify()→ 报错:TypeError: Request with GET/HEAD method cannot have body或静默失败 -
忘记设
Content-Type→ 后端收不到req.body(尤其 Express 需要express.json()中间件) -
用
GET发 JSON? → 不合法。JSON 数据应放在body,只用于POST/PUT/PATCH
? 补充:Node.js 环境下运行(如用 VS Code + Node)
Node 默认无 fetch,可快速补上:
npm install node-fetch
然后代码开头加:
import fetch from 'node-fetch'; // ES 模块(.mjs)或
// const fetch = require('node-fetch'); // CommonJS(.js)
不复杂但容易忽略细节,按上面任一示例复制,改掉 URL 和 data,就能立刻发出标准 JSON 请求。











