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