【问题标题】:Unable to fetch array from HTML form in expressJS无法从 expressJS 中的 HTML 表单中获取数组
【发布时间】:2017-02-27 21:03:52
【问题描述】:

我正在将 PHP 后端转换为 NodeJS。在 PHP 中,我编写了一个表单,其中使用数组发送多个相似类型的数据(例如您过去访问过的地方),我知道几乎相似的 JS 版本适用于 ExpressJS。但是,每当我尝试访问该变量时,它都会打印出“未定义”,并且数组的长度属性也不起作用。 ExpressJS 代码:

router.post('/hello', function(req, res)
{
 var locations = [];

 var apple = ["apple", "banana"];
 var name = req.body.name;
 locations = req.body.location;
 console.log(name + " <<>> "+ locations);
 console.log(apple);
 return;
});

以下代码返回以下输出:

POST /new/hello - - ms - -
Bangladesh <<>> undefined
[ 'apple', 'banana' ]

HTML 表单如下:

<form role="form" action="/new/hello" method="POST">

    <div class="form-group">
    <label for="email"> Trek name: </label>
    <input type = "text" class = "form-control"name="name">
    </div>

    <div class="form-group">
    <label for="location">trek_location 1: </label>
    <input type="text" class="form-control" id="text" name="location[]">
    </div>

    <div class="form-group">
    <label for="location">trek_location 2: </label>
    <input type="text" class="form-control" id="text" name="location[]">
    </div>

    <div class="form-group">
    <label for="location">trek_location 3: </label>
    <input type="text" class="form-control" id="text" name="location[]">
    </div>

    <div class="form-group">
    <label for="location">trek_location 4: </label>
    <input type="text" class="form-control" id="text" name="location[]">
    </div>

    <button type ="submit" class="btn btn-default"> Submit </button>
    </form>

我在我的 Php 后端使用了同样的表单,并且效果很好。我用谷歌搜索了很多,从表单中获取数组的方法在任何地方都是相同的。但是,它对我不起作用!

【问题讨论】:

    标签: javascript php arrays node.js express


    【解决方案1】:

    我已经成功地完成了你想要达到的目标,我的代码在两个方面与你的不同:

    1. 在我的 HTML 表单中,输入名称不包含数组括号,即我的 HTML 如下所示:

    2. 我正在使用一个名为 bodyparser 的快速中间件(我想我在某处读到它已经预装在最新的快速版本中,但可能值得一试。)

    此外,还有一个警告:如果您有多个位置发送到后端,您会得到一个不错的数组。如果您只有一个位置,您将获得那个元素,而不是包含该元素的数组。所以一定要在后端检查这个。

    【讨论】:

    • 很高兴我能帮上忙 :)
    猜你喜欢
    • 2016-09-24
    • 2021-08-31
    • 1970-01-01
    • 2019-04-13
    • 2017-12-09
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    相关资源
    最近更新 更多