Sai Ram
Sai Ram

Reputation: 4392

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');
      }
  });
});

Upvotes: 0

Views: 1842

Answers (2)

Manohar Reddy Poreddy
Manohar Reddy Poreddy

Reputation: 27515

I had a similar issue, but there is no key (not json), it was xml body
The solution is here: https://stackoverflow.com/a/45709414/984471

Upvotes: 0

Swaraj Giri
Swaraj Giri

Reputation: 4037

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

Upvotes: 1

Related Questions