I am going through the book Web Development with Node and Express and have hit a snag.
I was instructed to put the below in my application file, but it looks like body-parser
is deprecated and will not work. How can I achieve the same functionality?
This is my current code:
app.use(require('body-parser')());
app.get('/newsletter', function(req, res){
// we will learn about CSRF later...for now, we just
// provide a dummy value
res.render('newsletter', { csrf: 'CSRF token goes here' });
});
app.post('/process', function(req, res){
console.log('Form (from querystring): ' + req.query.form);
console.log('CSRF token (from hidden form field): ' + req.body._csrf);
console.log('Name (from visible form field): ' + req.body.name);
console.log('Email (from visible form field): ' + req.body.email); res.redirect(303, '/thank-you');
});
No need to install body-parser with express , but you have to use it if you will receive post request.
body parser package is deprecated. If you are using latest version of express you don't have to install body-parser package.
Explanation: The default value of the extended option has been deprecated, meaning you need to explicitly pass true or false value. Note for Express 4.16. 0 and higher: body parser has been re-added to provide request body parsing support out-of-the-box.
From: bodyParser is deprecated express 4
It means that using the bodyParser() constructor has been deprecated, as of 2014-06-19.
app.use(bodyParser()); //Now deprecated
You now need to call the methods separately
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
And so on.
Just wanted to update this thread because I tried the solution above and receieved undefined. Express 4.16+ has implemented their own version of body-parser so you do not need to add the dependency to your project. You can run it natively in express
app.use(express.json()); // Used to parse JSON bodies
app.use(express.urlencoded()); // Parse URL-encoded bodies using query-string library
// or
app.use(express.urlencoded({ extended: true })); // Parse URL-encoded bodies using qs library
Source
query string vs qs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With