Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpressJS Error: Body-Parser Deprecated

Question I'm trying build a Node.js API, when write my server.js file, my code looks like this:

var express = require('express');
var express = require('body-parser');

var app = express();
app.use(bodyParser.json());

app.get('/api/posts', function(req,res) {
res.json([
    {
        username: 'oscar',
        body: 'hello'
    }

])
})

app.listen(3000, function() {
console.log('Server Listening on', 3000)
})

However, in the command prompt I am getting this error:

body-parser deprecated bodyParser: use individual json.urlencoded
middlewares server.js:4:11
body-parser deprecated undefined extended: provide extended option
node_modules\body-parser\index.js:85:29

I tried changing this to :

app.use(bodyParser.urlencoded({ extended: true }));

and

app.use(bodyParser.urlencoded({ extended: false }))

like other posts suggest, but it still gives the same error. Not sure what to do now! Please help.

Thanks!

like image 782
Richard WU Avatar asked May 28 '15 04:05

Richard WU


People also ask

Is body parser deprecated in Express?

“bodyparser is deprecated 2021” Code Answer's // If you are using Express 4.16+ you don't have to import body-parser anymore.

Is Express JS deprecated?

It has been deprecated since v4. 11.0, and Express 5 no longer supports it at all.

Do I need body parser with Express?

This piece of middleware was called body-parser and used to not be part of the Express framework. The good news is that as of Express version 4.16+, their own body-parser implementation is now included in the default Express package so there is no need for you to download another dependency.

Why we use Bodyparser in node JS?

Body-parser is the Node. js body parsing middleware. It is responsible for parsing the incoming request bodies in a middleware before you handle it.


3 Answers

You don't need body-parser module any more with current express.js versions (≥ 4.16).

Instead, use the json parser already included in express:

app.use(express.json())

Source: https://expressjs.com/en/changelog/4x.html#4.16.0

like image 145
JSchirrmacher Avatar answered Oct 08 '22 01:10

JSchirrmacher


Don't use body-parser

In new versions of express, body parsing is now builtin. So, you can simply use

app.use(express.json()) //For JSON requests
app.use(express.urlencoded({extended: true}));

from directly express

You can uninstall body-parser using npm uninstall body-parser



Then you can simply get the POST content from req.body

app.post("/yourpath", (req, res)=>{

    var postData = req.body;

    //Or for string JSON body, you can use this

    var postData = JSON.parse(req.body);
});
like image 27
Abraham Avatar answered Oct 08 '22 02:10

Abraham


var app = express();

// configure body-parser

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
like image 23
HDK Avatar answered Oct 08 '22 00:10

HDK