Nodejs Post請求報socket hang up錯誤的解決辦法

admin發表於2017-03-28

在模擬實現post提交功能的時候,可能會出現socket hang up錯誤。

出現此問題的很大的一個原因就是請求頭設定的問題,傳送選項中需要加上headers欄位資訊。

修正後的完整程式碼如下:

[JavaScript] 純文字檢視 複製程式碼
var querystring = require('querystring'),
    http = require('http');
var data = querystring.stringify({
  info:'hi',
  test:5
});
var opt = {
  hostname:'www.test.com',
  port :9094,
  path:'/perationSqlQuery',
  method: 'POST',
  headers: {   
    'Content-Type':'application/x-www-form-urlencoded',
    'Content-Length': data.length  
  } 
};
var req = http.request(opt, function (res) {  
  res.on('data', function (data) {
    console.log(data.toString());
  });
});
req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});
req.write(data);
req.end();

相關文章