[英]Unable to fetch array from HTML form in expressJS
我正在将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后端使用了相同的表格,并且有效。 我已经用谷歌搜索了很多,到处都是从表单获取数组的方法是相同的。 但是,它对我不起作用!
我已经成功完成了您要实现的目标,并且我的代码在两个方面与您的代码有所不同:
在我的HTML表单中,输入名称不包含数组括号,即我的HTML如下所示:
我正在使用一种称为bodyparser
的快速中间件(我想我读过某个地方,它已经在最新的快速版本中预装了,但是可能值得一试。)
此外,还有一个警告:如果您有多个位置发送到后端,则会得到一个不错的数组。 如果只有一个位置,则将获得该元素,而不是包含该元素的数组。 因此,请确保在后端进行检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.