ChatGPT解决这个技术问题 Extra ChatGPT

bodyParser is deprecated express 4

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

B
Ben Fortune

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


@eslammostafa You can use bodyparser, you just can't call the constructor. You need to call each individual method.
@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.
What does extended do?
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.
bodyParser itself is now marked as deprecated and is available as part of express, see Sridhar's answer stackoverflow.com/a/59892173/196869, express.json()
M
Muhammad Adeel

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.


I use this, still getting the "body-parser deprecated" message. app.use(bodyParser.json()).use(bodyParser.urlencoded({ extended: true }));
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-nodejs
Thanks this work's for me, but i have a question! So, now we don't need to install body-parser?
Still deprecated at express@4.17.1
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.
S
Sridhar

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

Means we don't need to install body parser anymore??
yeah. we dont it as seperate package, since it is now available as a part of express.
im getting SyntaxError: Unexpected token n in JSON at position 6 at JSON.parse ()
A
Abraham

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


V
Vaidh

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()
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.
My console says I still have to pass extended to express.urlencoded({extended: true}) using express 4.17.1
@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 .
H
Hitesh Joshi

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

I think you wanted to say "body-parser was middleware " ? express is not middleware as I understand
J
John Haugeland

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.


L
Lakpriya Senevirathna

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

L
Laurel

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

B
Basheer AL-MOMANI

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

Will this help?
a
aashray jain

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 :-

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

It will run.

Happy Coding!


A
Aathi

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

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now