參考nodejs官網(wǎng)發(fā)送http post請(qǐng)求的方法,實(shí)現(xiàn)了一個(gè)模擬post提交的功能。實(shí)際使用時(shí)報(bào)socket hang up錯(cuò)誤。
后來發(fā)現(xiàn)是請(qǐng)求頭設(shè)置的問題,發(fā)送選項(xiàng)中需要加上headers字段信息(這個(gè)估計(jì)也和對(duì)方的服務(wù)器有關(guān),對(duì)于不完成的post請(qǐng)求頭,可能被丟棄了)。
完整的代碼如下(遇到類型問題的同學(xué)可以做個(gè)參考):
復(fù)制代碼 代碼如下:
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();
新聞熱點(diǎn)
疑難解答
圖片精選