Rounak
Rounak

Reputation: 95

Why the req object needs to parsed in Express?

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.

Upvotes: 0

Views: 49

Answers (2)

Gaëtan Boyals
Gaëtan Boyals

Reputation: 1228

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.

Upvotes: 1

Heiko Theißen
Heiko Theißen

Reputation: 16728

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.

Upvotes: 1

Related Questions