Express 中 req.body 为 undefined:已加 body-parser 仍无效
结论
如果 body-parser 已经安装,req.body 为 undefined 最常见的原因是:客户端用 fetch 发送 JSON 时没有设置 Content-Type: application/json。bodyParser.json() 只会解析请求头为 application/json 的请求体;缺少这个请求头时,解析器会跳过该请求,req.body 就可能一直是 undefined。
原因
前端用 JSON.stringify({ email, password }) 发送的是 JSON 字符串,但请求里没有 headers。fetch 不会因为 body 是字符串就自动设置 Content-Type: application/json,默认值通常也不是 JSON。服务端虽然用了:
app.use(bodyParser.json())
但它依赖客户端声明 Content-Type: application/json。同时启用的 urlencoded 处理的是表单编码请求,与 JSON 请求不同,不能替代 JSON 解析。
修改前端
为 fetch 加上 headers:
async ({request}) => {
let formData = await request.formData();
let email = formData.get("email");
let password = formData.get("password");
let register = await fetch("http://localhost:3000/register", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ email, password })
});
console.log(register.status);
return register;
}
如果 formData.get() 在 TypeScript 中返回的不是 string,可以按项目里的类型定义做转换,比如 String(formData.get("email")),但不要因此改变最终发送的 JSON 结构。
服务端检查
当前中间件顺序在 /register 路由之前,基本没问题。也可以用 Express 内置的 express.json() 替代 body-parser 的 json() 中间件:
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
如果继续使用 body-parser,确认解析器不是注册在路由之后。CORS 中间件建议放在解析器前面,方便统一处理预检请求;不过它不是这次 req.body 为 undefined 的主要原因。
验证
可以在 /register 里先打印请求头:
app.post("/register", (req: Request, res: Response) => {
console.log(req.headers["content-type"]);
console.log(req.body);
res.send("Form submitted");
});
正常情况下,这里应该能看到 application/json,并且 req.body 里有 email 和 password。如果仍然是 undefined,再检查是否有反向代理、网关,或者前端实际发出的请求覆盖了 headers。
备注:内容仅供参考。
