Post请求未在Nodejs中更新MongoDB中的标头信息

huangapple go评论80阅读模式
英文:

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,
};

Post请求未在Nodejs中更新MongoDB中的标头信息

英文:

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,
 
};

Post请求未在Nodejs中更新MongoDB中的标头信息

答案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());

huangapple
  • 本文由 发表于 2023年5月28日 10:40:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76349736.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定