Node.js 三種http請求方法
在工程實踐中,為了保證安全性等問題經常會在後台進行網路請求,在node.js中我會用到三種方法進行網路請求。
superagent,這個代理模塊還是很不錯的,使用方法也很簡單。
superagent.agent()
.post(api)
.type( fm )
.set( HEADERS )
.send( params )
.end( function( err,result){
console.log("請求結束");
if(err){
return callback( err, null);
}else{
return callback( null, result);
}
})
其中api為請求地址,fm為form或者json,params為請求參數。雖然使用方便,但是在使用中還是會遇到一些問題,比如請求過多時出現bug,無法處理或者正確接收返回。具體原因我也沒深究,平常使用起來還是沒問題的,可能是header沒配置好。
Advertisements
request請求模塊,request請求模塊與superagent差不多,使用也很簡單,github或者百度也有很好的介紹,在這裡就為大家推薦一下
最後說到的是node本身的http模塊,這個模塊還是很不錯的,目前沒遇到過bug或者無法處理請求的問題。
var postData = querystring.stringify(params)
var options = {
hostname:'123.57.136.110',
port:'8181',
path:api,
method:'POST',
headers:{
'Accept':'application/json, text/javascript, */*; q=0.01',
Advertisements
'Accept-Encoding':'gzip, deflate',
'Accept-Language':'zh-CN,zh;q=0.8',
'Connection':'keep-alive',
'Content-Length':postData.length,
'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8',
'Cookie':'',
'Host':'127.0.0.1',
'Origin':'127.0.0.1',
'Referer':'http://www.imooc.com',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75Safari/537.36',
'X-Requested-With':'XMLHttpRequest'
}
}
var req = http.request(options,function(res){
var buffers = [];
res.on('data',function(chunk){
buffers.push(chunk);
})
res.on('end',function(){
return callback(null,buffers);
})
})
req.on('error',function(e){
return callback(e,null);
})
req.write(postData)
req.end();
只需要正確設置好header和請求地址,請求參數就ok了,返回的數據是buffer形式,所以都push進了buffer里,數據接收完畢之後也就是end之後將數據返回就可以了。