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

body-parser parse undefined body into 'undefined'

Open KhaledMosaad opened this issue 8 months ago • 2 comments

Environment information

Version: 2.2.0

Platform: Linux khalid 6.13.8-arch1-1 #1 SMP PREEMPT_DYNAMIC Sun, 23 Mar 2025 17:17:30 +0000 x86_64 GNU/Linux

Node.js version: v22.12.0

Any other relevant information:

What steps will reproduce the bug?

Our project used morgan for logging in this way app.use(morgan(jsonFormat, { stream: Logger.stream })); morgan logging have a custom jsonFormat function to customize our logs, inside it we use this line body: stringifyFields(JSON.parse(tokens.body(req, res)) ?? {}), to log the body of the response, for requests that return no body we expect the tokens.body(req,res) to return null or undefined but in the new version of body-parser the returned value is invalid json string instead of null or undefined so the JSON.parse throw exception because it can not parse it the JSON.parse error:

SyntaxError: Unexpected token 'u', "
     undefined" is not valid JSON
        at JSON.parse (<anonymous>)

this is might be also tested by many ways other than that Note: morgan version is the same, we didn't change it

KhaledMosaad avatar Apr 08 '25 06:04 KhaledMosaad

+1 on this. Looks like as of v2 request.body is now undefined instead of an empty object

sacummings91 avatar Jun 02 '25 21:06 sacummings91

This seems to be done deliberately. The change was introduced in 6cbc279dc875ba1801e9ee5849f3f64e5b42f6e1 a very long time ago and released with v2.

I was also surprised by this change when updating to the new version. Is this behavior to be reverted/changed or should we adjust our code to accommodate for it?

RTiK avatar Jun 04 '25 07:06 RTiK

  • This was a deliberate change. (see issue)
  • Unfortunately, it was not highlighted very well in the release info and history.md -- we will address that.
  • To continue using v2, you'll want to update your code to check for undefined or typeof for 'object', etc.
    • additional error handling (e.g. try/catch) around any JSON parsing is always a good idea as well
  • v1 is still supported, so you can continue to use v1 if you want the previous behavior

ctcpip avatar Jul 03 '25 15:07 ctcpip