bodyParser is deprecated express 4
Asked Answered
B

13

689

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);
Barrio answered 20/6, 2014 at 14:48 Comment(1)
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.Gypsy
K
1001

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().

Koopman answered 20/6, 2014 at 15:7 Comment(23)
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());Baudin
is it still safe to use bodyParser ?Nowhere
@eslammostafa You can use bodyparser, you just can't call the constructor. You need to call each individual method.Koopman
@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, andrewkelley.me/post/do-not-use-bodyparser-with-express-js.html i will use formidable then for multipart forms.Nowhere
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.Koopman
Works as of July 2014 on latest builds of node, express and bodyparser.Laster
What does extended do?Heterosporous
extended - parse extended syntax with the qs module. (default: true), though they've deprecated the default option.Koopman
Sucks that I don't see anything in the docs about using extended: trueItalianize
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?Inartistic
They need to stop changing this for little reason, it's bloody annoyingCapacity
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.Mandragora
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!Sheriff
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?Elongate
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.Koopman
@BenFortune how do i use express.json()/urlencoded() i tried it but if i return req.json({data: req.body}) i get {} in postmanSweatbox
@MayankSingh Exactly the same way you'd use bodyParser.json/urlencoded.Koopman
@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?Sweatbox
@BenFortune nvm for somereason express is not taking form-data from postman only xxx-encoded and raw, thank you anyway.Sweatbox
@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). github.com/expressjs/body-parser/tree/…Vail
bodyParser itself is now marked as deprecated and is available as part of express, see Sridhar's answer https://mcmap.net/q/63579/-bodyparser-is-deprecated-express-4, express.json()Bogbean
@BenFortune Can you please update the answer for 2020?Schorl
this doesn't work in the latest version, check this answerBlinkers
P
463

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.

Palatal answered 21/6, 2014 at 18:46 Comment(5)
I use this, still getting the "body-parser deprecated" message. app.use(bodyParser.json()).use(bodyParser.urlencoded({ extended: true }));Harwell
That's right, I get a deprecation warning accessing the constructor. It is included in Express 4.17 as a dependency): nodejs.dev/learn/get-http-request-body-data-using-nodejsExercise
Thanks this work's for me, but i have a question! So, now we don't need to install body-parser?Kamenskuralski
Still deprecated at [email protected]Interline
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.Greenroom
E
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());
Ebony answered 24/1, 2020 at 7:33 Comment(3)
Means we don't need to install body parser anymore??Setsukosett
yeah. we dont it as seperate package, since it is now available as a part of express.Ebony
im getting SyntaxError: Unexpected token n in JSON at position 6 at JSON.parse (<anonymous>)Lepore
S
80

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

Skirt answered 25/6, 2021 at 7:45 Comment(0)
I
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.

Iloilo answered 13/3, 2021 at 10:52 Comment(4)
It's interesting because underneath express.json() use the same deprecated body-parse.json()Kurtzig
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.Iloilo
My console says I still have to pass extended to express.urlencoded({extended: true}) using express 4.17.1Mitchelmitchell
@Mitchelmitchell 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 .Iloilo
C
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());
Cleon answered 17/11, 2014 at 6:53 Comment(1)
I think you wanted to say "body-parser was middleware " ? express is not middleware as I understandMaw
F
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.

Fusain answered 4/11, 2016 at 15:57 Comment(0)
H
9

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());
Hinch answered 23/5, 2021 at 21:42 Comment(0)
A
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);
    });
Antonyantonym answered 17/5, 2016 at 20:49 Comment(0)
K
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
Kinnard answered 26/5, 2017 at 11:56 Comment(1)
Will this help?Madwort
C
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!

Contrast answered 1/3, 2021 at 11:36 Comment(0)
W
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});
});
Woodshed answered 30/9, 2021 at 22:41 Comment(0)
E
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=

Etna answered 10/11, 2022 at 16:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.