body-parser icon indicating copy to clipboard operation
body-parser copied to clipboard

Migration Guide V1 -> V2

Open whoisstan opened this issue 5 months ago • 1 comments

Description

For an empty http request body the v1 json parser would provide a {} request body. V2 provides an undefined body

Expectations

This to be described as it can cause all kinds of issues and errors. If you have done that and I missed it, sorry.

If you expect for example a username entry:

if (req.body.username){
   // do something
}

It has to change to something like this

if (req.body?.username){
   // do something
}

I added a workaround to not have to change lot's of code

const bodyParser        = require('body-parser'),
      express           = require('express'),
      json_reviver      = require('../../lib/json_reviver')

function jsonWithDefault(options) {
  const jsonParser = bodyParser.json(options);
  return (req, res, next) => {
    jsonParser(req, res, (err) => {
      if (err) return next(err);
      if (req.body === undefined) {
        req.body = {};   // restore v1 behavior
      }
      next();
    });
  };
}

module.exports = {
  jsonParser: jsonWithDefault({ limit: '5mb', reviver: json_reviver }),
  urlEncoded: bodyParser.urlencoded({ extended: true, limit: '5mb' }),
  raw:   express.raw({
    inflate: true,
    limit: '50mb',
    type: () => true, // this matches all content types
  })
};

whoisstan avatar Aug 23 '25 02:08 whoisstan

👍 This was a deliberate change in V2. And was also mentioned in another issue: https://github.com/expressjs/body-parser/issues/605#issuecomment-3032757427

nguyentoanit avatar Sep 17 '25 03:09 nguyentoanit