我有这个代码,它将活跃用户发布的内容发送到mongodb id of the post + author + author ID + caption(what the author write)中,代码运行得很好,但是这个语句caption : req.body.caption,不断向mongodb返回null的问题,我真的不知道为什么或如何解决这个问题,
发布代码如下:
router.post("/publish", function (req, res, next) {
// Generate a random id
User.findById(req.user.id, function (err, user) {
if (!user) {
req.flash('error', 'No account found');
return res.redirect('/login');
} else {
}
user.posts.push({
_id: guid.raw(),
author: user.userName,
authorID: user.id,
caption : req.body.caption,
comments: [],
likes: [],
createdAt: new Date(),
lastEditedAt: new Date()
});
user.save(err => {
if (err) throw err;
console.log("Post saved");
res.redirect("/");
});
});
});caption的模式如下:
caption :{type : String}ejs部分也在下面。
<input
type="text"
id="caption"
name="caption"
class="form-control"
placeholder="enter your posts"
value="Share your thoughts!"
/>请帮帮忙,
诚挚的问候,
发布于 2020-04-18 20:39:40
来自console.log(req.body)的输出--一个空的body对象--毫无疑问地证明在您的帖子中没有表单字段到达您的路由处理程序。
您可能需要告诉express使用几个中间件模块来解析POST请求正文中的数据。尝试在调用app.use('/', router)之前将这两行代码放在代码中的某个位置。
app.use(express.json())
app.use(express.urlencoded({ extended: false }))这将使express使用表单中的数据填充req.body对象。它根据Content-Type:报头选择JSON或url编码。
或者,您的html (ejs)可能没有包装在<form....>对象中的<input...>字段。您可以通过在浏览器的Network选项卡中查看POST请求来判断这是否是真的。如果单击POST请求,您将找到一个名为Form Data的部分。如果它是空的,则您的表单帖子不发送任何内容。如果caption字段为空,则该字段未包装在<form ...>标记中。
https://stackoverflow.com/questions/61288588
复制相似问题