Sai Ram Sai Ram - 1 year ago 39
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.


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


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;'/action', function (req, res) {

app.get('/', function (req, res) {

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

Answer Source

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