0
var fs = require('fs');
var http = require('http');
var qs = require('querystring');
var util = require("util");

while am running following code am getting

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: socket hang up
    at createHangUpError (http.js:1472:15)
    at Socket.socketOnEnd [as onend] (http.js:1568:2
    at Socket.g (events.js:175:14)
    at Socket.EventEmitter.emit (events.js:117:20)
    at _stream_readable.js:920:16
    at process._tickCallback (node.js:415:13)

code

var sendresult = function (result) {
    console.log(result)
    var post_data ={"result": result};
    console.log(JSON.stringify(post_data))
  var options = {
    host: '172.16.2.107',
    path: '/senddata',
    port: '9080',
    method: 'POST',
      headers : {
        'Content-Type': 'application/json',     
        'Content-Length': post_data.length
    }     

  };
 console.log("INSIDE-------------------------------------------------------")
    var post_req = http.request(options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
          console.log('Response: ' + chunk);
      });

        req.on('error', function (err) {
    //handle error here
});
  });

  // post the data
  post_req.write(post_data.toString());
  post_req.end();

}
sendresult("dataaaaaaaaa")

whats wrong with my code

Psl
  • 3,830
  • 16
  • 46
  • 84

1 Answers1

0

For one thing, post_data.length does not exist because post_data is not a string.

So change this:

var post_data ={"result": result};

to this:

var post_data = JSON.stringify({"result": result});

And you should really use Buffer.byteLength(post_data) instead of post_data.length for your Content-Length in case post_data should ever contain utf8 characters or similar. Buffer.byteLength() always calculates byte count whereas string.length returns character count, which may not always be the same as the byte count.

mscdex
  • 104,356
  • 15
  • 192
  • 153