1

I found 2 methods to get the Post Body data in Node.js

Below is the 2 webservice Post methods, so which is preferred approach that needs to be followed while fetching the data from client through rest api in Node.js or is there any other approach to read post data.

1st Method

//http://localhost:1337/api/postparams1
//Content-Type: application/x-www-form-urlencoded
//param1=complete+reference&param2=abcd+1234
function postparams1(req, res) 
{
    var result = 
    {
        Url : req.originalUrl,
        Method : req.method,
        Param1 : req.body.param1,
        Param2 : req.body.param2
    };

    res.status(200).send(result);
}

2nd Method

//http://localhost:1337/api/postparams2
//{
//    "param1" : "param value 1",
//    "param2" : "param value 2"
//}
function postparams2(req, res) 
{
    var data = '';
    req.setEncoding('utf8');  

    req.on('data', function (chunk) {
        data += chunk;
        console.log("In data : " + data);
    });

    req.on('end', function () {
        console.log("In end : " + data);

        var newObj = JSON.parse(data);

        newObj.Url = req.originalUrl;
        newObj.Method = req.method,

        res.status(200).send(newObj);

    });
}
Sharath
  • 2,348
  • 8
  • 45
  • 81

2 Answers2

1

I think first option is more common beacause needs less code but you need to use Express.

Express 3 code:

app.use(express.bodyParser());

app.post('/', function(request, response){
 console.log(request.body.param1);
 console.log(request.body.param2);
});

Express 4 code:

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/', function(request, response){
 console.log(request.body.param1);
 console.log(request.body.param2);
});

See more info here:

Extract post data in node

Community
  • 1
  • 1
cesarluis
  • 897
  • 6
  • 14
  • In Express 4 (the most recent version), [`body-parser`](https://github.com/expressjs/body-parser) is a separate module. – robertklep Aug 12 '15 at 10:04
0
    var req = https.get("url", function(response) {
          var str = ''
          response.on('data', function (chunk) {
            str += chunk;
          });
          response.on('end', function () {
             console.log(str);
          });
    });
    req.end();
    req.on('error', function(e) {
       console.error(e);
    });
Deepak
  • 141
  • 1
  • 2