英文:
Post Request not updating header info in MongoDB using Nodejs
问题
我试图编写一个非常基本的POST请求,使用Mongoose存储提醒和提醒的状态。
例如:{"name":"喝水", "completed":false}
在Postman上测试API时,给定的POST请求只会在数据库中输入**__id和_v**,头部信息未更新。请查看代码并帮助我纠正它。
模型
const mongoose = require("mongoose");
const TaskSchema = new mongoose.Schema({
name: String,
completed: Boolean
});
module.exports = mongoose.model("Task", TaskSchema);
任务控制器
const Task = require("../models/Task");
const getAllTasks = (req, res) => {
res.send("获取所有可用任务");
};
const createTask = async (req, res) => { // POST请求的代码
const task = await Task.create(req.body);
res.status(201).json({ task });
};
module.exports = {
getAllTasks,
createTask,
};
英文:
I am trying to write a very basic POST request that stores a reminder and the status of the reminder using Mongoose.
e.g. {"name":"Drink Water", "completed":false}
While testing the API on Postman the given POST request only enters the __id and _v in the database, the header info is not updated. Kindly look into the code and help me correct it.
Model
const mongoose = require("mongoose");
const TaskSchema = new mongoose.Schema({
name: String,
completed: Boolean
});
module.exports = mongoose.model("Task", TaskSchema);
Task Controller
const Task = require("../models/Task");
const getAllTasks = (req, res) => {
res.send("Get all Available Tasks");
};
const createTask = async (req, res) => { // code for POST req.
const task = await Task.create(req.body);
res.status(201).json({ task });
};
module.exports = {
getAllTasks,
createTask,
};
答案1
得分: 1
你需要应用 express.json()
中间件以能够读取请求体。
你可以在路由之前将以下行添加到你的主文件中:
app.use(express.json());
英文:
You need to apply express.json()
middleware to be able to read request body.
Can you add the following line to your main file before routes?
app.use(express.json());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论