ibtehaz ibtehaz - 6 months ago 7
PHP Question

(SOLVED) Unable to fetch array from HTML form in expressJS

I am converting a Php backend to NodeJS. In PHP, I wrote a form where I used an array to send multiple similar type of data (like places you have visited in the past), I was aware the almost similar JS version would work for ExpressJS. However, whenever, I try to access the variable, it is printing out "undefined" and the length property of array is also not working.
ExpressJS code:

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;
});


The following code returns the following output:

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


The HTML form is given below:

<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>


I have used this very same form for my Php backend and that worked. I have googled a lot and everywhere the method is same to fetch array from the form. However, it is not working for me!
Any help will be appreciated.
Thank you :)

Answer

I have successfully done what you are trying to achieve, and my code differs from yours in two areas:

  1. In my HTML form, the input name does not contain the array brackets, i.e. my HTML looks like this:

  2. I'm using an express middleware called bodyparser (I think I read somewhere that this is already preloaded in the newest express version, but it might be worth a try.)

Also, there is a caveat with this: If you have multiple locations sent to the backend, you get a nice array. If you only have one location, you will get that one element, not an array containing the element. So make sure to check this in the backend.

Comments