sachin
sachin

Reputation: 14385

How can i get the post data in Node.js?

Server1.js

var data = querystring.stringify({
    imageName: reqImgName
  });

var options = {
              host: 'localhost',
              port: 4321,
              path: '/image',
              method: 'POST',
              headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Content-Length': data.length
                }
            };

server2.js

http.createServer(function(req, res){
  var reqMethod=req.method;
  var request = url.parse(req.url, true);
  var pathName = request.pathname;
  console.log('Path name is '+pathName);
  if (reqMethod=='POST' && pathName == '/image') {

   //here i need my server1 data..how can i get here.
   } 

}).listen(4321);

Upvotes: 0

Views: 3042

Answers (2)

c.P.u1
c.P.u1

Reputation: 17094

var postData = '';
req.on('data', function(datum) {
  postData += datum;
});

req.on('end', function() {
  //read postData
});

You are not getting any post data because you're not sending any in server1.js. Try writing some data to the request body

var req = http.request(options, function(res) {

});


req.write('data=somedata');

Another way of debugging your server2 is to make a browser initiate a POST request to /image

Upvotes: 5

icktoofay
icktoofay

Reputation: 129139

Attach event listeners to the data and end events of req. data will give you chunks of data which you can incrementally process, and end will tell you when you've got everything.

Upvotes: 1

Related Questions