详解nodejs通过代理(proxy)发送http请求(request)
有可能有这样的需求,需要node作为web服务器通过另外一台http/https代理服务器发http或者https请求,废话不多说直接上代码大家都懂的:
varhttp=require('http')
varopt={
host:'这里放代理服务器的ip或者域名',
port:'这里放代理服务器的端口号',
method:'POST',//这里是发送的方法
path:'https://www.google.com',//这里是访问的路径
headers:{
//这里放期望发送出去的请求头
}
}
//以下是接受数据的代码
varbody='';
varreq=http.request(opt,function(res){
console.log("Gotresponse:"+res.statusCode);
res.on('data',function(d){
body+=d;
}).on('end',function(){
console.log(res.headers)
console.log(body)
});
}).on('error',function(e){
console.log("Goterror:"+e.message);
})
req.end();
这样我们就通过了指定代理服务器发出了https的请求,注意这里我们同代理服务器是http协议的,不是https,返回的结果当然肯定会根据你的代理服务器不同有所不同。
Gotresponse:302
{location:'https://www.google.com.tw/',
'cache-control':'private',
'content-type':'text/html;charset=UTF-8',
'set-cookie':
['PREF=ID=b3cfcb24798a7a07:FF=0:TM=1356078097:LM=1356078097:S=v_3qEd0_gCW6-xum;expires=Sun,21-Dec-201408:21:37GMT;path=/;domain=.google.com',
'NID=67=qoJf_z3W7KlibpNZ6xld__r0rYGyYu7l_XiDQmZ3anjBFadDzhijME3QcX651yucne_irK_2JMS8HF5FuxNl85mE0nDrtn9Iq0z2gW69n00OrB970hpHTbYe0mAogZit;expires=Sat,22-Jun-201308:21:37GMT;path=/;domain=.google.com;HttpOnly'],
p3p:'CP="ThisisnotaP3Ppolicy!Seehttp://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657formoreinfo."',
date:'Fri,21Dec201208:21:37GMT',
server:'gws',
'content-length':'223',
'x-xss-protection':'1;mode=block',
'x-frame-options':'SAMEORIGIN',
via:'1.0***.****.com:80(squid/2.6.STABLE21)',
'proxy-connection':'keep-alive'}
302Moved
302Moved
Thedocumenthasmoved
here.
谷歌返回了一个302,告诉我们进行跳转,需要访问https://www.google.com.tw/这个地址
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。