0

I'm trying to get a JSON data which is sent as JSON data using postman tool and trying to receive it my post() method.

    var express = require('express');
    var app = express();

    app.post('/myData',function(req,res){
        console.log("--->",req.body);
    });

var server = app.listen(8080,function(){});

This is the JSON data sent through postman tool

I'm getting undefined in my console as "---> undefined"

Control type is set

I'm trying to retrieve the JSON data set in my postman tool to either my console or browser

This is the error in terminal

Grijan
  • 220
  • 2
  • 16
  • 1
    Possible duplicate of [How to access the request body when POSTing using Node.js and Express?](https://stackoverflow.com/questions/11625519/how-to-access-the-request-body-when-posting-using-node-js-and-express) – 31piy Dec 04 '17 at 09:24

3 Answers3

1

Corrected. Please try to run this code.

var express = require('express');
var app = express();

app.post('/myData', function (req, res) {

    req.on('data', function (data) {
        console.log("--->",data.toString());
        res.send("Received");
    });
});

var server = app.listen(8080, function () { });
Mika Sundland
  • 14,170
  • 16
  • 31
  • 44
Datta
  • 91
  • 6
  • I have run this code on my machine. It is working fine.. Please check it. – Datta Dec 04 '17 at 09:46
  • Tried this also, says that ReferenceError : body is not defined again! – Grijan Dec 04 '17 at 09:50
  • Sorry mate, i made a mistake in the code, THANK you so much, i got the answer and this is the first time i got an answer through stackoverflow website, Thanks a million!!!!!!!!!!!!!!!!!!!!!! – Grijan Dec 04 '17 at 09:54
  • And i would like to know if possible how you solved that by using that specific code, sorry im new to node!!!!! – Grijan Dec 04 '17 at 10:25
  • 1
    I am currently working in bigdata and nodejs. Thats why – Datta Dec 04 '17 at 11:54
0

Add res.send(req.body); inside the app.post method.

    app.post('/myData',function(req,res){
        console.log("--->",req.body);
        res.send(req.body);
    });
MMakela
  • 127
  • 2
  • 13
0

Express usually uses a middleware called body-parser to parse the received JSON content. req.body will be empty if you don't enable body-parser or something similar. body-parser is built in for the latest versions of Express. It's enabled like this:

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

So the final code is like this:

var express = require('express');
var app = express();

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

app.post('/myData',function(req,res){
    console.log("--->", req.body);
    res.send('data received');
});

var server = app.listen(8080,function(){});

I've also added res.send('data received');, because you should send a response when you get a request on a valid endpoint.

Mika Sundland
  • 14,170
  • 16
  • 31
  • 44