686

I am using express 4.0 and I'm aware that body parser has been taken out of the express core, I am using the recommended replacement, however I am getting

body-parser deprecated bodyParser: use individual json/urlencoded middlewares server.js:15:12 body-parser deprecated urlencoded: explicitly specify "extended: true" for extended parsing node_modules/body-parser/index.js:74:29

Where do I find this supposed middlewares? or should I not be getting this error?

var express     = require('express');
var server      = express();
var bodyParser  = require('body-parser');
var mongoose    = require('mongoose');
var passport    = require('./config/passport');
var routes      = require('./routes');

mongoose.connect('mongodb://localhost/myapp', function(err) {
    if(err) throw err;
});

server.set('view engine', 'jade');
server.set('views', __dirname + '/views');

server.use(bodyParser()); 
server.use(passport.initialize());

// Application Level Routes
routes(server, passport);

server.use(express.static(__dirname + '/public'));

server.listen(3000);
Melbourne2991
  • 11,707
  • 12
  • 44
  • 82
  • 5
    Note for future readers, OP's script uses ```var server = express()```, but when reading (seemingly ALL of) the answers below, assume that the line ```var app = express()``` was used. – Partik May 05 '21 at 17:14

13 Answers13

996

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

app.use(bodyParser.urlencoded());

app.use(bodyParser.json());

And so on.

If you're still getting a warning with urlencoded you need to use

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

The extended config object key now needs to be explicitly passed, since it now has no default value.

If you are using Express >= 4.16.0, body parser has been re-added under the methods express.json() and express.urlencoded().

Ben Fortune
  • 31,623
  • 10
  • 79
  • 80
  • I have the same warning after updating `body-parser` to `1.4.3` and `express` to `4.4.4`. The line that gives the warning: `app.use(bodyParser.urlencoded());` – kasztelan Jun 21 '14 at 17:08
  • is it still safe to use bodyParser ? – shehata Jul 23 '14 at 21:57
  • 2
    @eslammostafa You can use bodyparser, you just can't call the constructor. You need to call each individual method. – Ben Fortune Jul 23 '14 at 22:37
  • 2
    @BenFortune thanks Ben, i got it, i was just worried the /tmp thing, but now i checked again, the /tmp problem happens only if we used bodyParser to parse multipart forms, http://andrewkelley.me/post/do-not-use-bodyparser-with-express-js.html i will use formidable then for multipart forms. – shehata Jul 23 '14 at 22:51
  • Multipart should only be used when you have file input elements in your form, which bodyparser doesn't support since it doesn't support file uploads. – Ben Fortune Jul 24 '14 at 09:08
  • Works as of July 2014 on latest builds of node, express and bodyparser. – Stephan Kristyn Jul 28 '14 at 10:00
  • 34
    What does `extended` do? – Camilo Martin Aug 22 '14 at 09:35
  • `extended - parse extended syntax with the qs module. (default: true)`, though they've deprecated the default option. – Ben Fortune Aug 22 '14 at 10:00
  • Sucks that I don't see anything in the docs about using `extended: true` – nak Aug 28 '14 at 17:59
  • 1
    an explanation of the difference would be helpful. I also see below that you can just use both. But why? What considerations should you make? – Harry Moreno Dec 24 '14 at 00:27
  • They need to stop changing this for little reason, it's bloody annoying – Jonathan. Jun 01 '15 at 21:29
  • 22
    The best way I explain extended true is that not using extended means that `curl --data "user[email]=foo&user[password]=bar" localhost:3000/login` would be received by the server in `req.body` as `{ user[email]: "foo", ...}` whereas `req.body` would be `{user: {email: "foo", ... }}` with `extended: true`. – reed_de_la_mer Jun 12 '15 at 02:48
  • Wow! Thank you so much for breaking it down. Got rid of all those dumb deprecated warnings. All my my form data is coming through! – buycanna.io Nov 29 '15 at 22:32
  • Would someone kindly explain, whether you would still include the statement `app.use(bodyParser.json())` even after you make `extended: true`. So basically would `bodyParser.urlencoded({extended: true})` still need you to have `app.use(bodyParser.json())`.. or would this statement only be required if `extended: false`? – Grateful Oct 05 '16 at 11:12
  • 1
    They're not really related. If you're going to be parsing forms you'll need `bodyParser.urlencoded`, if you have multidimensional forms then you'll want `extended: true` with that. If you're going to be parsing JSON then you need `bodyParser.json`. – Ben Fortune Oct 05 '16 at 11:23
  • @BenFortune how do i use express.json()/urlencoded() i tried it but if i return req.json({data: req.body}) i get {} in postman – Mayank Singh Fartiyal Jan 25 '18 at 09:22
  • @MayankSingh Exactly the same way you'd use `bodyParser.json/urlencoded`. – Ben Fortune Jan 25 '18 at 09:26
  • @BenFortune I am using it like app.use(express.json()) and it is returning empty object, Just to be clear since i am using express.json i dont need to bodyparser explicitely since it is using it under the hood? – Mayank Singh Fartiyal Jan 25 '18 at 11:43
  • @BenFortune nvm for somereason express is not taking form-data from postman only xxx-encoded and raw, thank you anyway. – Mayank Singh Fartiyal Jan 25 '18 at 11:52
  • @CamiloMartin The `extended` option allows to choose between parsing the URL-encoded data with the `querystring` library (when `false`) or the `qs` library (when `true`). https://github.com/expressjs/body-parser/tree/1.19.0#bodyparserurlencodedoptions – Yuriy Rypka Dec 01 '20 at 09:05
  • 20
    bodyParser itself is now marked as deprecated and is available as part of express, see Sridhar's answer https://stackoverflow.com/a/59892173/196869, `express.json()` – Jim Mar 15 '21 at 15:15
  • @BenFortune Can you please update the answer for 2020? – RoboticRenaissance Mar 29 '21 at 22:25
  • this doesn't work in the latest version, check [this answer](https://stackoverflow.com/questions/24330014/bodyparser-is-deprecated-express-4/59892173#59892173) – dota2pro May 28 '21 at 11:27
461

Want zero warnings? Use it like this:

// Express v4.16.0 and higher
// --------------------------
const express = require('express');

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

// For Express version less than 4.16.0
// ------------------------------------
const bodyParser = require('body-parser');

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

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.

Muhammad Adeel
  • 2,877
  • 1
  • 22
  • 18
Jan Peša
  • 6,760
  • 4
  • 27
  • 32
  • 6
    I use this, still getting the "body-parser deprecated" message. `app.use(bodyParser.json()).use(bodyParser.urlencoded({ extended: true }));` – Jeremy Thille Feb 20 '15 at 10:55
  • That's right, I get a deprecation warning accessing the constructor. It is included in Express 4.17 as a dependency): https://nodejs.dev/learn/get-http-request-body-data-using-nodejs – Konkret Jul 07 '21 at 22:03
  • Thanks this work's for me, but i have a question! So, now we don't need to install body-parser? – AllisLove Sep 14 '21 at 04:05
  • 1
    Still deprecated at express@4.17.1 – Rafael Sep 17 '21 at 23:56
  • With express 4.16+ body-parser is need no longer be installed or used hence the deprecation warning. express no directly contains json and urlencoded middle ware. – wheredidthatnamecomefrom Sep 25 '21 at 01:16
233

If you're using express > 4.16, you can use express.json() and express.urlencoded()

The express.json() and express.urlencoded() middleware have been added to provide request body parsing support out-of-the-box. This uses the expressjs/body-parser module module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers.

Source Express 4.16.0 - Release date: 2017-09-28

With this,

const bodyParser  = require('body-parser');

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

becomes,

const express = require('express');

app.use(express.urlencoded({ extended: true }));
app.use(express.json());
Sridhar
  • 11,466
  • 5
  • 39
  • 43
77

Don't use body-parser

If you are using Express 4.16+ You can do it just like this with express:

app.use(express.urlencoded({extended: true}));
app.use(express.json()) // To parse the incoming requests with JSON payloads

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



To get the POST content, you can use req.body

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

    var postData = req.body;

    //Or if this doesn't work

    var postData = JSON.parse(req.body);
});

I hope this helps

Abraham
  • 12,140
  • 4
  • 56
  • 92
43

Even I faced the same issue. The below change I mentioned resolved my problem.

If you're using Express 4.16+ version, then

  • You may have added a line to your code that looks like the following:

app.use(bodyparser.json()); //utilizes the body-parser package
  • You can now replace the above line with:

app.use(express.json()); //Used to parse JSON bodies

This should not introduce any breaking changes into your applications since the code in express.json() is based on bodyparser.json().

  • If you also have the following code in your environment:

app.use(bodyParser.urlencoded({extended: true}));
  • You can replace the above line with:

app.use(express.urlencoded()); //Parse URL-encoded bodies
  • If you're getting a warning saying that you still need to pass extended to express.urlencoded() then, do update the above code as:

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

A final note of caution:

You might not need to install the additional body-parser package to your application if you are using Express 4.16+. There are many tutorials that include the installation of body-parser because they are dated prior to the release of Express 4.16.

  • It's interesting because underneath `express.json()` use the same deprecated `body-parse.json()` – Maksim Novikov Apr 21 '21 at 14:56
  • Yeah! But somehow the `express.JS` development team has simplified the json parsing strategy / configuration by just replacing one line of code with the other which syntactically doesn't make much a difference. – iCantFindaGoodUsername Apr 28 '21 at 13:28
  • My console says I still have to pass `extended` to `express.urlencoded({extended: true})` using express 4.17.1 – Hache_raw May 16 '21 at 18:36
  • @Hache_raw I'm not sure but I guess that depends if you have somehow made the use of **UTF-8 encoding** or perhaps, it is indeed now changed. It'd be better if you refer to this [express.js urlencoding link doc](http://expressjs.com/en/api.html#express.urlencoded) . – iCantFindaGoodUsername May 18 '21 at 19:40
17

In older versions of express, we had to use:

app.use(express.bodyparser()); 

because body-parser was a middleware between node and express. Now we have to use it like:

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
Hitesh Joshi
  • 63
  • 1
  • 10
himanshu yadav
  • 1,818
  • 2
  • 13
  • 5
9

body-parser is a piece of express middleware that reads a form's input and stores it as a javascript object accessible through req.body 'body-parser' must be installed (via npm install --save body-parser) For more info see: https://github.com/expressjs/body-parser

   var bodyParser = require('body-parser');
   app.use(bodyParser.json()); // support json encoded bodies
   app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

When extended is set to true, then deflated (compressed) bodies will be inflated; when extended is set to false, deflated bodies are rejected.

John Haugeland
  • 9,230
  • 3
  • 37
  • 40
Parth Raval
  • 4,097
  • 3
  • 23
  • 36
8

Instead of bodyParser.json(), simply use express.json(), You don't want to install body-parser

For an instance,

const express = require("express");

const app = express();
app.use(express.json());
Lakpriya Senevirathna
  • 2,488
  • 2
  • 17
  • 35
1

I found that while adding

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

helps, sometimes it's a matter of your querying that determines how express handles it.

For instance, it could be that your parameters are passed in the URL rather than in the body

In such a case, you need to capture both the body and url parameters and use whichever is available (with preference for the body parameters in the case below)

app.route('/echo')
    .all((req,res)=>{
        let pars = (Object.keys(req.body).length > 0)?req.body:req.query;
        res.send(pars);
    });
Laurel
  • 5,965
  • 14
  • 31
  • 57
Ian Mbae
  • 138
  • 1
  • 2
  • 13
1

What is your opinion to use express-generator it will generate skeleton project to start with, without deprecated messages appeared in your log

run this command

npm install express-generator -g

Now, create new Express.js starter application by type this command in your Node projects folder.

express node-express-app

That command tell express to generate new Node.js application with the name node-express-app.

then Go to the newly created project directory, install npm packages and start the app using the command

cd node-express-app && npm install && npm start
Basheer AL-MOMANI
  • 14,473
  • 9
  • 96
  • 92
1

body-parser deprecated bodyParser: use individual json/urlencoded middlewares node_modules\express\lib\router\layer.js:95:5

express deprecated req.host: Use req.hostname instead node_modules\body-parser\index.js:100:29

body-parser deprecated undefined extended: provide extended option node_modules\body-parser\index.js:105:29

No need to update express or body-parser

These errors will be removed. Follow these steps :-

  1. app.use(bodyParser.urlencoded({extended: true})); // This will help in encoding.
  2. app.use(bodyParser.json()); // this will support json format

It will run.

Happy Coding!

aashray jain
  • 301
  • 3
  • 3
1

Check this answer Stripe webhook error: No signatures found matching the expected signature for payload

// Use JSON parser for all non-webhook routes
app.use((req, res, next) => {
  if (req.originalUrl === '/webhook') {
    next();
  } else {
    express.json()(req, res, next);
  }
});

// Stripe requires the raw body to construct the event
app.post('/webhook', express.raw({type: 'application/json'}), (req, res) => {
  const sig = req.headers['stripe-signature'];

  let event;

  try {
    event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
  } catch (err) {
    // On error, log and return the error message
    console.log(`❌ Error message: ${err.message}`);
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }

  // Successfully constructed event
  console.log('✅ Success:', event.id);

  // Return a response to acknowledge receipt of the event
  res.json({received: true});
});
Aathi
  • 2,599
  • 2
  • 19
  • 16
0

In my case it was typescript + vs code marking it wrongly as deprecated: enter image description here

But if you check the source code:

/** @deprecated */
declare function bodyParser(
    options?: bodyParser.OptionsJson & bodyParser.OptionsText & bodyParser.OptionsUrlencoded,
): NextHandleFunction;

declare namespace bodyParser {

you see it should be the constructor, not the namespace. So either typescript or vs code is getting it wrong. All good, there's no deprecation happening in this case (bodyParser as namespace=

estani
  • 24,254
  • 2
  • 93
  • 76