首页 文章

无法从expressJS中的HTML表单中获取数组

提问于
浏览
0

我正在将Php后端转换为NodeJS . 在PHP中,我写了一个表单,我使用一个数组发送多个相似类型的数据(比如你过去访问过的地方),我知道几乎相似的JS版本适用于ExpressJS . 但是,每当我尝试访问变量时,它都会打印出“undefined”,并且数组的length属性也不起作用 . 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后端,这是有效的 . 我google了很多,到处都是方法相同,从表单中获取数组 . 但是,它不适合我!

1 回答

  • 1

    我已成功完成您要实现的目标,我的代码在两个方面与您的代码不同:

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

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

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

相关问题