Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-deprecated alternative to body-parser in Express.js

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');
});
like image 239
Lance Hietpas Avatar asked May 08 '15 14:05

Lance Hietpas


People also ask

Do you still need body parser with Express?

No need to install body-parser with express , but you have to use it if you will receive post request.

Is body parser deprecated 2021?

body parser package is deprecated. If you are using latest version of express you don't have to install body-parser package.

What does bodyParser deprecated mean?

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.


2 Answers

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.

like image 131
Alex Alksne Avatar answered Oct 24 '22 15:10

Alex Alksne


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

like image 34
JLee365 Avatar answered Oct 24 '22 14:10

JLee365