Sai Ram Sai Ram - 4 months ago 7
Node.js Question

unable to get request.body in express

I am playing with express and trying to understand the basic work of form submission and I am unable to get data on req.body(gives empty object).Here is the html and js file I am using.

HTML File

<form class="form-horizontal" id="form" action="/action" method="post" role="form">
<h2>Registration Form</h2>
<div class="form-group">
<label for="firstName" class="col-sm-3 control-label">Full Name</label>
<div class="col-sm-9">
<input type="text" id="firstName" placeholder="Full Name" class="form-control" autofocus="">
<span class="help-block">Last Name, First Name, eg.: Smith, Harry</span>
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-3 control-label">Email</label>
<div class="col-sm-9">
<input type="email" id="email" placeholder="Email" class="form-control">
</div>
</div>
</form>


and

Javascript File

var express = require('express');
var bodyParser = require('body-parser');
var app = express();


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


var MongoClient = require('mongodb').MongoClient;
var myCollection;

app.post('/action', function (req, res) {
console.log("----------------------",req.body);
res.send("done");
});

app.get('/', function (req, res) {
res.sendFile(__dirname+"/signup.html");
});

app.listen(3000, function () {
console.log('Example app listening on port 3000!');
var db = MongoClient.connect('mongodb://127.0.0.1:27017/test',
function(err, db) {
if(err)
throw err;
else{
console.log("connected to the mongoDB !");
myCollection = db.collection('test_collection');
}
});
});

Answer

Form inputs need to have a name for bodyparser to build req.body

Add name to firstname and email input fields.

<input type="email" id="email" placeholder="Email" class="form-control" name="email">
<input type="text" id="firstName" placeholder="Full Name" class="form-control" autofocus="" name="firstName">