{ “error”: “无法解构 'req.body' 的属性 'title',因为它未定义。”

{ "error": "Cannot destructure property 'title' of 'req.body' as it is undefined." }

提问人:Suman Gotame 提问时间:9/3/2023 最后编辑:Aqib ChatthaSuman Gotame 更新时间:9/6/2023 访问量:87

问:

以下是 Node.js 应用程序的代码片段:

// src/models/workoutsModel.js
const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const workoutSchema = new Schema({
  title: {
    type: String, // Corrected to String
    required: true,
  },
  reps: {
    type: Number,
    required: true,
  },
  load: {
    type: Number,
    required: true,
  },
}, { timestamps: true });

module.exports = mongoose.model("workout", workoutSchema);

// src/Routes/workout.js
const express = require("express");
const Workout = require("../Model/workoutsModel");

const router = express.Router();

router.get("/", (req, res) => {
  res.json({ message: "route for all workouts" });
});

router.get("/:id", (req, res) => {
  res.json({
    message: "getting single routes",
  });
});

router.post("/", async (req, res) => {
  try {
    const { title, reps, load } = req.body;
    const workout = await Workout.create({ title, reps, load });
    res.status(200).json(workout);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

router.delete("/:id", (req, res) => {
  res.json({
    message: "deleting workouts",
  });
});

router.patch("/:id", (req, res) => {
  res.json({
    message: "updating workouts",
  });
});

module.exports = router;

// sr/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("/api/workouts", workoutRoutes);

app.use(express.json());

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");
  }); 

任何人都可以在这里为我提供一些帮助吗?目前,我正在尝试使用 express.json(),但是当我尝试解构请求正文时,它似乎没有按预期工作。我遇到了一个问题,但不确定如何解决。如果有人对使用 express.json() 进行解构有经验或见解,并能提供一些指导或建议,我将不胜感激。

node.js 表示 mern 析构函数

评论

0赞 opeonikute 9/3/2023
这回答了你的问题吗?Express.js req.body 未定义
0赞 Marco 9/3/2023
请编辑帖子以格式化您提供的代码 meta.stackoverflow.com/questions/251361/...

答:

0赞 CherryDT 9/6/2023 #1

正文解析中间件插入到某些路由之后,因此这些较早的路由不会看到任何解析的正文。

确保您的中间件安装在 .express.json()workoutRoutes