【问题标题】:undefined output from body-parser来自正文解析器的未定义输出
【发布时间】:2021-12-15 21:16:29
【问题描述】:

我正在尝试使用 node.js 中的 body-parser 将用户输入从客户端获取到服务器端。我使用 express 作为我的应用程序的基础。

这是服务器端代码:

app.post('/register', urlencodedParser, (req, res) => {
console.log("The text is: " + req.body.url)})

这是我试图从中提取输入的 html 表单:

 <form class="modal-dialog" action="/register" method="POST">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addModalLabel">Add comics</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-primary" role="alert">
                        Curently the amount of URL's supported is limited. Check out info page for more detailed
                        info.
                    </div>
                    <div class="form-group">
                        <label for="url">URL of comics</label>
                        <input type="text" class="form-control" id="url" aria-describedby="urlHelp"
                            placeholder="Enter URL">
                        <small id="urlHelp" class="form-text text-muted">For detailed guide on how to find URL go to
                            info
                            page.</small>
                    </div>
                    <div class="form-group">
                        <label for="exampleFormControlTextarea1">Description</label>
                        <textarea class="form-control" id="description" rows="3"></textarea>
                    </div>
               
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Add</button>
                </div>
            </div>
        </form>

问题是输出未定义。我是 node.js 的新手,所以这可能是一个简单的问题,但我被困了很长一段时间,所以请不要评判。

【问题讨论】:

    标签: javascript node.js body-parser


    【解决方案1】:

    在表单的 input 字段中,node.js 重新识别这些字段的方式是在前端的输入中指定 name 字段。像这样:

    <input type="text" class="form-control" id="url" name="url" aria-describedby="urlHelp"
    

    现在在后端,因为您的路由是 .post 函数,您可以使用 req.body.url 访问它,您已经在这样做了!

    【讨论】:

      【解决方案2】:

      您应该在输入中添加name 属性:&lt;input name="url" … /&gt;。只有具有name 属性的表单元素才会在提交表单时传递其值。

      【讨论】:

        【解决方案3】:

        您没有分享您设置服务器的方式。首先,body-parser 已弃用,您可以使用 express 指定中间件,如下所示:

        app.use(express.urlencoded({ extended: true }));
        

        urlencoded是解析HTML表单数据所需的解析器。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-03-26
          • 2017-04-23
          • 1970-01-01
          • 2021-02-01
          • 2016-10-01
          • 1970-01-01
          • 2022-07-21
          • 1970-01-01
          相关资源
          最近更新 更多