Posting form data with Nodejs and body-parser

Richard picture Richard · Jul 15, 2015 · Viewed 14.4k times · Source

I have followed a couple of different online attempts at this now and I keep getting undefined for my post data and console.log(JSON.stringify(req.body)) returns nothing also.. So I am going wrong somewhere...

HTML:

<!DOCTYPE HTML>
<html>
  <head>
    <title>Chat</title>
  </head>
  <body>
    <form action="/" method="post">
      <button>Close</button><br/><br/>
      <label for="username">Your Name: *</label><br/>
      <input id="username" type="text" value="" name="username" autocomplete="off" required="required" /><br/>
    <!--   <label for="email">Email: *</label><br/>
      <input id="email" value="" name="email_address" autocomplete="off" required="required" /><br/> -->
      <label for="phone">Phone:</label><br/>
      <input id="phone" value="" name="phone" autocomplete="off" /><br/>
      <label for="question">Question: </label><br/>
      <textarea id="question" name="question">
      </textarea required="required"><br/><br/>
      <button type="submit">Chat</button>
    </form>
  </body>
</html>

JS:

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

app.use(bodyParser.json());

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

app.post('/', function(req, res) {
    var username = req.body.username;
    res.send('<h1>Hello</h1> '+username);
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

Answer

michelem picture michelem · Jul 15, 2015

Try to add Urlencoded option:

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

// Add this line below
app.use(bodyParser.urlencoded({ extended: false })) 

app.use(bodyParser.json());

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

app.post('/', function(req, res) {
    var username = req.body.username;
    res.send('<h1>Hello</h1> '+username);
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});