Junaidi
Junaidi

Reputation: 21

NodeJS - Getting form post data

I am a newbie in NodeJs. Trying to figure out why the following code is not working for me. I am basically trying to do a simple post from an HTML file. It works fine if I send the post request from curl, or if I use AJAX post. Would like to know what's wrong with the following post.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<form method="post" action="http://localhost:3000/">
    <table>
        <tr>
            <td><input type="text" id="txtOne"/></td>
        </tr>
        <tr>
            <td>
                <input type="submit" value="Submit Data">
            </td>
        </tr>
    </table>
</form>
</body>
</html>

My node.js file is

var express   =     require("/usr/local/bin/node_modules/express");
var bodyParser  =    require("/usr/local/bin/node_modules/body-parser");
var app       =     express();
app.use(bodyParser.urlencoded({ extended: false }));

app.get('/',function(req,res){
    res.sendfile("mypage.html");
});

app.post('/',function(req,res){
    var str = req.body.txtOne;
    console.log("From Client POST request: Text = " + str);
    res.end(str);
});

app.listen(3000);

I am getting str value as undefined.

Upvotes: 0

Views: 262

Answers (2)

E.K
E.K

Reputation: 120

var str = req.body.txtOne;

you are searching for the input that has name="txtOne"

id works only for the DOM

<td><input type="text" name="txtOne"/></td>

Upvotes: 0

PatrickD
PatrickD

Reputation: 1156

First of all, your form field needs a name value instead of a id. So change

 <td><input type="text" id="txtOne"/></td>

to

 <td><input type="text" name="txtOne"/></td>

Upvotes: 1

Related Questions