admin管理员组

文章数量:1323731

I want to get value from a form: Here's the form:

<form method='post' action='/stack'>
     <input name="stack0" value="stackoverflow0"/>
     <input name="stack1" value="stackoverflow1"/>
     <button type='submit'>Click</button>
</form>

if we want to get the value from the form we use:

app.post('/stack',function(req,res){
     var tmp = req.body.stack0;
     var tmp1 = req.body.stack1;

     console.log(tmp)  // stackoverflow0
     console.log(tmp1)  // stackoverflow1
});

I wont use this method because i have a lot of values, i want something like loop,

for(var i=0;i<2;i++){
    var tmp = req.body.stack(i); // any syntaxe like that ?

    console.log(tmp)  // souldstackoverflow0 if i==0,  souldstackoverflow1 if i==1
}

when i take 0; should tmp take req.body.stack0, and when i==1 tmp = req.body.stack1 ? help plz, and thnx :)

I want to get value from a form: Here's the form:

<form method='post' action='/stack'>
     <input name="stack0" value="stackoverflow0"/>
     <input name="stack1" value="stackoverflow1"/>
     <button type='submit'>Click</button>
</form>

if we want to get the value from the form we use:

app.post('/stack',function(req,res){
     var tmp = req.body.stack0;
     var tmp1 = req.body.stack1;

     console.log(tmp)  // stackoverflow0
     console.log(tmp1)  // stackoverflow1
});

I wont use this method because i have a lot of values, i want something like loop,

for(var i=0;i<2;i++){
    var tmp = req.body.stack(i); // any syntaxe like that ?

    console.log(tmp)  // souldstackoverflow0 if i==0,  souldstackoverflow1 if i==1
}

when i take 0; should tmp take req.body.stack0, and when i==1 tmp = req.body.stack1 ? help plz, and thnx :)

Share Improve this question asked Apr 11, 2015 at 21:23 RedaReda 571 gold badge1 silver badge7 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

You have to use the bracket notation to access the object properties if you want to loop over them with a variable in the name:

for(var i=0;i<2;i++){
    var tmp = req.body['stack' + i];

    console.log(tmp) 
}

We have to use BodyParser to grab data from the input field. Code is here HTML code

 <form class="" action="/" method="post">
 <input type="text" name="newItem" value="" placeholder="Please enter your task">
 <button type="submit" name="button">Add</button>
const express = require('express');

const bodyParser = require('body-parser')

const app = express();

app.use(bodyParser.urlencoded({extended: true}));

var temp = req.body.newItem; console.log(temp)

本文标签: javascriptGet value from input in NodeJSStack Overflow