Manivannan Manivannan - 1 month ago 10
Node.js Question

nodejs request.body returns empty object {}

I am using following code, request.body returns

{}
i would expect my output as
{username:"Mani",password:"pass"}
please help me to fix if anything wrong in this code sample.

app.js



var bodyParser = require('body-parser');
var express = require('express');
var app = express();

app.use(bodyParser.urlencoded({ extended: false }));

app.post('/', function(request, response){
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});

app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});


npm version:

express 4.14.0

body-parser 1.15.2

url http://localhost:3000/

method: POST

header: Content-Type: application/json

request payload : {username:"Mani",password:"pass"}

output of app.js console is {}

Answer

It appears that your body is a json document. You will need to configure body-parser to accept json:

app.use(bodyParser.json());