首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >req.body.caption返回null

req.body.caption返回null
EN

Stack Overflow用户
提问于 2020-04-18 19:49:30
回答 1查看 216关注 0票数 1

我有这个代码,它将活跃用户发布的内容发送到mongodb id of the post + author + author ID + caption(what the author write)中,代码运行得很好,但是这个语句caption : req.body.caption,不断向mongodb返回null的问题,我真的不知道为什么或如何解决这个问题,

发布代码如下:

代码语言:javascript
复制
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的模式如下:

代码语言:javascript
复制
caption :{type : String}

ejs部分也在下面。

代码语言:javascript
复制
  <input
      type="text"
      id="caption"
      name="caption"
      class="form-control"
      placeholder="enter your posts"
      value="Share your thoughts!"
    />

MongoDB screen

请帮帮忙,

诚挚的问候,

EN

回答 1

Stack Overflow用户

发布于 2020-04-18 20:39:40

来自console.log(req.body)的输出--一个空的body对象--毫无疑问地证明在您的帖子中没有表单字段到达您的路由处理程序。

您可能需要告诉express使用几个中间件模块来解析POST请求正文中的数据。尝试在调用app.use('/', router)之前将这两行代码放在代码中的某个位置。

代码语言:javascript
复制
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 ...>标记中。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61288588

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档