Joseph Chien Joseph Chien - 6 months ago 115
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.use(bodyParser());

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>' +
'</form>';

res.send(html);
});

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

app.listen(80);


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

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

app.use(bodyParser.json()); 
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.