我正在尝试向服务器(mongodb)发出发布请求,但出现此错误:
UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“ todo_description”
我在本地主机上运行mongodb
// Require Express
const express = require("express");
// Setting Express Routes
const router = express.Router();
// Set Up Models
const Todo = require("../models/todo");
// Get All Todos
router.get("/", async (req, res) => {
try {
const todo = await Todo.find();
res.json(todo);
} catch (err) {
res.json({ message: err });
}
});
router.get("/:id", async (req, res) => {
try {
const id = req.params.id;
await Todo.findById(id, (err, todo) => {
res.json(todo);
});
} catch (err) {
res.json({ message: err });
}
});
router.post("/add", async (req, res) => {
const todo = new Todo({
todo_description: req.body.todo_description,
todo_responsible: req.body.todo_responsible,
todo_priority: req.body.todo_priority,
todo_completed: req.body.todo_completed,
});
try {
await todo.save();
res.json(todo);
} catch (err) {
res.json({ message: err });
}
});
router.patch("/update/:id", async (req, res) => {
try {
const updateTodo = await Todo.updateOne(
{ _id: req.params.id },
{ $set: { todo_description: req.body.todo_description } }
);
updateTodo.save().then(updateTodo => {
res.json(updateTodo);
});
} catch (err) {
res.json({ message: err });
}
});
router.delete("/delete/:id", async (req, res) => {
try {
const deleteTodo = await Todo.deleteOne({ _id: req.params.id });
res.json(deleteTodo);
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
我的待办事项模型
// Require Mongoose
const mongoose = require("mongoose");
// Define Schema
// const Schema = new mongoose.Schema;
// Define Todo-Schema
const TodoSchema = new mongoose.Schema({
// Creating Fields
todo_description: {
type: String
},
todo_responsible: {
type: String
},
todo_priority: {
type: String
},
todo_completed: {
type: Boolean
},
todo_date: {
type: Date,
default: Date.now
}
});
// Compile Model From Schema
// const TodoModel = mongoose.model("Todos", TodoSchema);
// Export Model
module.exports = mongoose.model("todos", TodoSchema);
错误消息:
(节点:548)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“ todo_description” 在router.post(C:\ Users \ kinG \ Desktop \ projects \ protoinofprototype \ mern \ backend \ routes \ todo.js:33:32) 在Layer.handle上[作为handle_request](C:\ Users \ kinG \ Desktop \ projects \ mountain-of-prototype \ mern \ backend \ node_modules \ express \ lib \ router \ layer.js:95:5)
谢谢
答案 0 :(得分:1)
您正在从todo_description
访问req.body
。仅当您添加req.body
中间件或自己添加类似的中间件时,body-parser
才可用。
在加载路线之前添加此内容:
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use(bodyParser.json());
您也可以将其添加到特定路线。进一步了解here。
答案 1 :(得分:0)
您应该在应用程序的主文件中使用body-parser。它在中间件解析主体之前为您提供了解析的json,默认情况下为字符串形式。并确保您在req.body中发送todo_description(使用前应检查)。
const bodyParser = require('body-parser');
app.use(bodyParser.json());