Req.body 不断返回一个空字段,即使在我的表单中填写了字段

编程入门 行业动态 更新时间:2024-10-04 01:22:22

Req.body 不断返回一个空<a href=https://www.elefans.com/category/jswz/34/1771443.html style=字段,即使在我的表单中填写了字段"/>

Req.body 不断返回一个空字段,即使在我的表单中填写了字段

我有一个表单,我想为我的鞋子写评论,然后通过 POST 请求将它发送到我的 node.js 服务器,但是我的 req.bodyment 一直返回一个空字符串,即使我的评论在表格已填写。

在我的路由文件中,我有以下代码行: router.post("/shoe/:id", shoe_controller.shoe_details_post);

然后在我实际的鞋子控制器文件中,这是我填写 shoe_details_post 函数的方式:

exports.shoe_details_post = [
  // Validate and sanitize comment field
  body("comment", "Comment must not be empty.")
    .trim()
    .isLength({ min: 1 })
    .escape(),
  // Process request after validation and sanitization

  asyncHandler(async (req, res, next) => {
    // Extract the validation errors from a request.
    const errors = validationResult(req);
    console.log(errors);

    const shoe = Shoe.findById(req.params.id);
    const comment = req.bodyment;

    console.log(req.body);

    // console.log("hi!" + shoe);
    console.log("comment:  " + comment);
    // console.log(req.user);

    res.redirect('/catalog');
  }),
];

我的表单页面如下所示: 扩展布局

block content
  h1 #{shoe.name}

  img(src=`/images/shoe_images/jordan4.jpeg`)

  form(method='POST' action='' enctype='multipart/form-data')
    div.form-group
      label(class="shoe-detail-comment-box" for='comment') Comment:
      textarea#summary.form-control(type='textarea', placeholder='Comment here', name='comment', required='true')
    button.btn.btn-primary(type='submit') Submit

我的 shoe_controller 文件中有另一种类似的方法,我在其中做了几乎完全相同的事情,但形式不同,效果很好,但由于某种原因,这个方法不行。在我的其他功能中,我还验证并清理了表单中的相应字段,并能够获取字段的值。然而,在这一篇中,无论我做什么,我的评论总是空的。

回答如下:

默认情况下,Express 不会读取任何请求的主体。它只读取标头并将主体留在流中等待一些知道如何处理特定内容类型的中间件或请求处理程序来读取和解析请求的主体。因此,您的表单数据到达了请求的主体,但您没有指定任何 Express 中间件来读取它。因此

req.body
仍然是空的。

要解决此问题,首先将表单内容类型更改为

application/x-www-form-urlencoded
multipart/form-data
可以工作,但它更难在服务器上编码,这里不需要(通常用于一个或多个文件上传,当表单有多个部分要上传时,表单内容加上附件)。

block content
  h1 #{shoe.name}

  img(src=`/images/shoe_images/jordan4.jpeg`)

  form(method='POST' action='' enctype='application/x-www-form-urlencoded')
    div.form-group
      label(class="shoe-detail-comment-box" for='comment') Comment:
      textarea#summary.form-control(type='textarea', placeholder='Comment here', name='comment', required='true')
    button.btn.btn-primary(type='submit') Submit

然后,您需要合适的 Express 中间件 来读取该内容类型。您可以这样添加:

app.use(express.urlencoded());

确保此中间件出现在表单的请求处理程序之前。您只需在 Express 服务器上指定一次,因为它将应用于所有与该内容类型匹配的传入请求。

这将告诉 express,只要它发现内容类型为

application/x-www-form-urlencoded
的任何请求,该中间件应该读取请求的主体,使用
application/x-www-form-urlencoded
中的预期编码解析它,并将解析结果放入
req.body 
然后数据将在您的请求处理程序中为您准备好。对于不是
application/x-www-form-urlencoded
的传入请求,中间件将不执行任何操作。

更多推荐

Req.body 不断返回一个空字段,即使在我的表单中填写了字段

本文发布于:2024-05-30 23:53:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771059.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   写了   表单   Req   body

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!