Quite often people end up getting “undefined” on their request body of a post method. If you are wondering why, then that is because you don’t have a middleware to parse the response. Look at the below code, this will print the request body as undefined.

var express = require("express");
var app = express();
app.post('/hello',function(req,res){
 	console.log(req.body)
	res.send("");
});
app.listen(8080);

Let us say we are expecting a JSON, we could use a body parser express.json() to parse the request body. Similarly for text, exprexx.text() etc. The below will print the request JSON body properly as we are using middleware to parse it.

var app = express();
app.use(express.json())
app.post('/hello',function(req,res){
 	console.log(req.body)
	res.send("");
});

We may also use the module body-parser to handle multiple types.

var bodyParser = require("body-parser");
app.use(bodyParser.json())

 

Express Request Body Undefined