1

I'm trying to get user input from a html form but can't retrieve the data. This is the HTML code:

<form action="/login" method="POST" enctype="application/x-www-form-urlencoded">
    <div class="form-group">
        <label for="username">Username</label>
        <input type="text" class="form-control" id="username" placeholder="Username">
    </div>
    <div class="form-group">
        <label for="password">Password</label>
        <input type="password" class="form-control" id="password" placeholder="Password">
    </div>
    <button type="submit" class="btn btn-default">Login</button>
</form>

And here is the Node.JS code:

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

var express = require('express');

var app = express();

app.use(bodyParser.json());

app.post('/login', function(req, res){
    console.log(req.body);
});

When I input data on the form, the post request returns {}. However, using Postman it works just fine...

Ivan Aguilar
  • 565
  • 1
  • 7
  • 22

2 Answers2

2

You need to use the bodyParser.urlencoded method to get it working.

Add the below snippet below your `app.use(bodyParser.json());' statement.

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

Hope this helps!

David R
  • 14,711
  • 7
  • 54
  • 72
0

After Express 4.16.0+

No need for body-parser package.

import express, { urlencoded } from 'express';

app.use(express.json());
app.use(urlencoded({ extended: true }));
somesh sam
  • 152
  • 2
  • 8