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

Issue

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');
});

Solution

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.

Answered By – Alex Alksne

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published