Express.json()解析异常:无法解构req.body属性的问题求助
解决Express中req.body未定义的问题
问题根源
你的代码里express.json()中间件是在挂载workout路由之后才注册的,Express的中间件按注册顺序执行,当请求到达/api/workouts的POST路由时,解析请求体的中间件还未生效,导致req.body为undefined,解构操作自然报错。
修复步骤
将app.use(express.json())移到挂载路由之前,确保所有路由都能使用这个解析请求体的中间件:
修改后的server.js代码:
require("dotenv").config(); const express = require("express"); const mongoose = require("mongoose"); const workoutRoutes = require("./Routes/workouts"); const app = express(); app.get("/", (req, res) => { res.json({ message: "you are on the root page" }); }); app.use((req, res, next) => { console.log(req.path, req.method); next(); }); // 先注册解析请求体的中间件 app.use(express.json()); // 再挂载业务路由 app.use("/api/workouts", workoutRoutes); mongoose .connect(process.env.URI) .then(() => { app.listen(process.env.PORT, () => { console.log( "connected to the database and listening on port", process.env.PORT ); }); }) .catch(() => { console.log("error connecting to the database"); });
额外检查项
- 发送POST请求时,必须设置请求头
Content-Type: application/json,否则express.json()不会解析请求体。 - 确认请求体确实包含
title、reps、load三个字段,避免后续mongoose数据验证报错。
内容的提问来源于stack exchange,提问作者Suman Gotame
相关产品推荐
相关产品推荐

