0

Below is the code I am using:

const express = require('express');
const fs = require('fs');

const app = express();

// MIDDLEWARE
app.use((req, res, next) => {
  console.log('Hello from the Middleware 1');
  console.log(req.body);

  next();
});

app.use(express.json());

app.use((req, res, next) => {
  console.log('Hello from the Middleware 2');
  console.log(req.body);

  next();
});

The first Middleware logs the req.body as undefined, but the 2nd Middleware logs the req.body as it is. I am new to Node.Js and I could not find the right explanation for this.

Rounak
  • 85
  • 2
  • 7

2 Answers2

1

You have three middlewares:

  • in the first, req.body is still undefined
  • the second is express.json(), this parses the request body and fills req.body accordingly
  • the third then logs req.body.
Heiko Theißen
  • 12,807
  • 2
  • 7
  • 31
1

The other answer address the "why it does not work", but not the original question, a.k.a "Why does req.body needs to be parsed".

The short answer is that you don't really know in advance if the body will be, effectively, a JSON object. The .json() basically ensures that you have a JSON as a body.

You can read a more thorough and better explanation on this S/O answer.

Please note that express switched from using a third-party library known as body-parser, to using their own .json() method.

Gaëtan Boyals
  • 1,193
  • 1
  • 7
  • 22
  • 1
    Got it. Thanks for explaining. Further, I tested the middleware by sending a request with just a text body, and the third middleware printed an empty object. So, if the request body type is not JSON then express.json() will just return an empty object. – Rounak Jan 06 '22 at 15:34