參考Node.js官網發送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();
關鍵就在 headers 這一段:明確聲明 Content-Type 為 application/x-www-form-urlencoded,並提供準確的 Content-Length。這樣對方服務器才能正確接收完整的請求體,不再出現 socket hang up。同時,加上 req.on('error', ...) 的事件監聽也是好習慣,便於在出問題時第一時間捕獲並定位錯誤信息。