由于某些原因,尝试发出发布请求时,请求正文未定义:
这是我的路由器:
router.route("/").post(schoolController.createSchool);
这是我在schoolController中为createSchool放置的内容:
exports.createSchool = async (req, res) => {
try {
console.log(req.body);
// return undefined
const newSchool = await School.create(req.body);
res.status(201).json({
status: "success",
data: {
school: newSchool,
},
});
} catch (err) {
res.status(400).json({
status: "fail",
message: err,
});
}
};
此外,我正在关注jonas的udemy上的nodejs课程,他几乎拥有与此完全一样的东西,除了它用于处理旅游请求而不是学校
答案 0 :(得分:0)
您在此处面临的问题可能是您没有正确配置body-parser中间件。普通{
unityId: 2393044, // It is a school
parentId: 239, // In this case, it is a city
grade: 7.3,
city: {
unityId: 239
parentId: 23
grade: 8.2,
},
state: {
unityId: 23
parentId: 2
grade: 7.5,
},
region: {
unityId: 2
parentId: 1
grade: 7.9,
},
country: {
unityId: 1
parentId: null
grade: 7.7,
},
}
将不包含名称为req
的任何属性。仅当请求通过主体解析器中间件时,body
键才会添加到body
中。您可以尝试使用控制台日志记录req
。如果请求已正确记录,则很有可能需要正确配置bodyparser中间件,然后才能在代码中使用req
。