Shooting Stars
Shooting Stars

Reputation: 835

Parsing the req.body from a POST request

I have created an app using Node.js, Express, Body-parser, and Handlebars. I am currently in a hypothetical situation where I have dynamically created x number of buttons based on x number of entries in a database.

This is how the buttons are created

<form method="POST" action="/favoriteCreator">
    <input type="submit" name="{{this.id}}" value="{{this.fname}} {{this.lname}}">
</form>

And this is what I do when I POST to the server

app.post('/favoriteCreator', function(req, res) {
    var button = req.body;
    console.log(req.body);
});

When I get the req.body it gives me back the correct information (The button name of 'this.id', and the button value of 'first name and last name'. The syntax is this:

{ '1': 'Tom Bradstreet' }
{ whatever id is: whatever firstname lastname is }

So I am getting the body, the problem is I don't know how to parse to get only the ID. When I try to do req.body.name I get undefined because well obviously .name would be referring to the actual string. So I'm having a problem getting the first element out of the request body since the name of each button is dynamically created. Any help would be appreciated.

Upvotes: 1

Views: 6879

Answers (3)

won't this work?

<form method="POST" action="/favoriteCreator/{{this.id}}">
    <input type="submit" name="{{this.id}}" value="{{this.fname}} {{this.lname}}">
</form>

then,

app.post('/favoriteCreator/:id', function(req, res) {
    var button = req.body;
    console.log(req.params.id);
});

Actually I am new to these and neglect me if this is wrong.

Upvotes: 0

Shooting Stars
Shooting Stars

Reputation: 835

As an aside, the answer by Randy is right. In my case I wanted to get the key but key[0] would return Tom Bradstreet intead of 1. What I had to do was,

    app.post('/favoriteCreator', function(req, res) {
    var keys = Object.keys(req.body);
    console.log(keys.toString());
});

if you do console.log(keys) it will give you an unusable array. In my case I got [ '1' ]. So I had to convert it using toString() to get 1. I'm not sure how safe toString() actually is in this case, but it is how I got to a usability state.

Upvotes: 0

Randy Casburn
Randy Casburn

Reputation: 14165

Use Object.keys(req.body); or use a for...of if just iterating without needing the keys.

Here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

let keys = Object.keys(req.body);
console.log(req.body[keys[0]]);

or here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

for(let item of req.body){
   console.log(item);
}

Upvotes: 2

Related Questions