【问题标题】:Data is always 'undefined' when POSTing form data through body-parser in node.js express通过 node.js express 中的 body-parser 发布表单数据时,数据总是“未定义”
【发布时间】:2019-07-01 18:15:07
【问题描述】:

为了清楚起见,我将表格简化为以下内容:

      <form method="post" action="/form" id="testform" enctype="application/x-www-form-urlencoded" name="testform" novalidate>
          <input type="text" class="form-control" id="name" >
          <button type="submit" class="btn btn-dark btn-lg">Generate XML</button>
      </form>

在我的主 js 文件中,我有以下内容:

var bodyParser = require('body-parser')

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: true })

我正在这里接收数据(或不接收,视情况而定):

.post('/form', urlencodedParser, function (req, res) {
    res.send('welcome, ' + req.body.name)
    console.log(req.body)
  })

我得到的只是“欢迎,未定义”,日志显示为空 - {}

这让我很生气,我该如何检查发送的内容?调试这太疯狂了!

【问题讨论】:

    标签: node.js forms express parsing body-parser


    【解决方案1】:

    我认为您缺少 &lt;input&gt; 元素上的 name 属性:

    <input type="text" class="form-control" id="name"  name="name">
    

    您已经设置了 id,但它只能用于 CSS 选择器 (#name)、链接(访问 #name 将选择该输入)和 &lt;label&gt; 元素(使用 for="name")。

    【讨论】:

    • AAAAAHHHH。它必须像这样愚蠢。谢谢谢谢我已经瞎了。我会在 js 中使用的关联按钮上设置名称属性,并在我的脑海中混合所有内容。
    • 这是最好的发展;p
    【解决方案2】:

    元素由服务器端的 name 参数识别。需要在输入标签中添加名称属性。

    【讨论】:

      【解决方案3】:

      为输入元素赋予name 属性为"name",代码就可以正常工作了。

      【讨论】:

        猜你喜欢
        • 2023-03-08
        • 1970-01-01
        • 2012-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-25
        • 1970-01-01
        • 2018-08-01
        相关资源
        最近更新 更多