Reputation: 95
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
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
Reputation: 16728
You have three middlewares:
req.body
is still undefinedexpress.json()
, this parses the request body and fills req.body
accordinglyreq.body
.Upvotes: 1