【问题标题】:Error: socket hang up错误:套接字挂起
【发布时间】:2014-08-27 04:33:40
【问题描述】:
var fs = require('fs');
var http = require('http');
var qs = require('querystring');
var util = require("util");

在运行以下代码时

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)

代码

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")

我的代码有什么问题

【问题讨论】:

    标签: node.js


    【解决方案1】:

    一方面,post_data.length 不存在,因为post_data 不是字符串。

    所以改变这个:

    var post_data ={"result": result};
    

    到这里:

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

    而且你真的应该使用Buffer.byteLength(post_data) 而不是post_data.length 作为Content-Length,以防post_data 应该包含utf8 字符或类似字符。 Buffer.byteLength() 始终计算字节数,而 string.length 返回字符数,可能并不总是与字节数相同。

    【讨论】:

      猜你喜欢
      • 2015-09-13
      • 2014-10-02
      • 2015-08-27
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      相关资源
      最近更新 更多