Joseph Chien Joseph Chien - 1 year ago 232
Node.js Question

Node JS Read form input with express

I have the following code that supposedly open a web page with one user input field, and use express to get and post display the user's input.

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


app.get('/', function(req, res){
var html = '<form action="/" method="post">' +
'Enter your name:' +
'<input type="text" name="userName" placeholder="..." />' +
'<br>' +
'<button type="submit">Submit</button>' +

});'/', function(req, res){
var userName = req.body.userName;
var html = 'Hello: ' + userName + '.<br>' +
'<a href="/">Try again.</a>';


However, I got the following error and I cannot figure out how to get it to work. Can someone give me a hint? Thanks!

Thu, 02 Jun 2016 15:10:23 GMT body-parser deprecated bodyParser: use
individual json/urlencoded middlewares at server.js:20:9 Thu, 02 Jun
2016 15:10:23 GMT body-parser deprecated undefined extended: provide
extended option at ....\node_modules\body-parser\index.js:105:29

Answer Source

The bodyParser() constructor has been deprecated (details here), you need to use these now :

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

When extended is set to true, it will use the qs library for parsing, and when set to false it will use querystring. Research the difference between the two to decide which one you want to use, I've always used qs without any issues.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download