Nodejs發送Post請求時出現socket hang up錯誤的解決辦法


參考nodejs官網發送http post請求的方法,實現了一個模擬post提交的功能。實際使用時報socket hang up錯誤。

后來發現是請求頭設置的問題,發送選項中需要加上headers字段信息(這個估計也和對方的服務器有關,對於不完成的post請求頭,可能被丟棄了)。

完整的代碼如下(遇到類型問題的同學可以做個參考):

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();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM