express throws error as `body-parser deprecated undefined extended`
In my node app, I am using express. all works fine, But i am getting error in the cmd
. I use all are updated modules...
my code :
var express = require('express');
var bodyParser = require('body-parser');
var jade = require('jade');
var app = express();
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded()); // to support URL-encoded bodies
app.get('/',function(req,res){
res.render('index.jade');
});
app.get('/login',function(req,res){
res.render('index.jade');
});
app.post('/login',function(req,res){
console.log(req.body);
});
app.get('/signup',function(req,res){
res.render('signup.jade');
});
var env = process.env.PORT || 3000;
app.listen(env, function(req, res){
console.log('i am working!');
});
Error:
D:\myLogin>node app
body-parser deprecated undefined extended: provide extended option app.js:11:20 //why i am getting this?
i am working!
{ username: '[email protected]', password: 'pass' } // i am getting response
Can any help me to understand this issue please?
Solution 1:
You have to explicitly set extended
for bodyParser.urlencoded()
since the default value is going to change in the next major version of body-parser
. Example:
app.use(bodyParser.urlencoded({ extended: true }));
Since express
4.16.0, you can also do:
app.use(express.urlencoded({ extended: true }))
Solution 2:
Attention: With express version => 4.16.0
the body-parser
middleware was added back under the methods express.urlencoded()
and express.json()
Which can be used as:
app.use(express.urlencoded({extended: true}));
app.use(express.json());
Solution 3:
The error says you need to provide the extended option for the body-parser like so:
app.use(bodyParser.urlencoded({ extended: false }))
Solution 4:
If you facing 'bodyParser' is deprecated.
Just do
app.use(express.urlencoded({extended: true}));
app.use(express.json());
Note: If you are using 4.16.0
or later express version.