nodejs通过代理(proxy)发送http请求(request)

有可能有这样的需求,需要node作为web服务器通过另外一台http/https代理服务器发http或者https请求,废话不多说直接上代码大家都懂的:

var http = require('http') var opt = { host:'这里放代理服务器的ip或者域名', port:'这里放代理服务器的端口号', method:'POST',//这里是发送的方法 path:' https://www.google.com', //这里是访问的路径 headers:{ //这里放期望发送出去的请求头 } } //以下是接受数据的代码 var body = ''; var req = http.request(opt, function(res) { console.log("Got response: " + 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("Got error: " + e.message); }) req.end();

这样我们就通过了指定代理服务器发出了https的请求,注意这里我们同代理服务器是http协议的,不是https,返回的结果当然肯定会根据你的代理服务器不同有所不同。

Got response: 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-2014 08:21:37 GMT; path=/; domain=.google.com', 'NID=67=qoJf_z3W7KlibpNZ6xld__r0rYGyYu7l_XiDQmZ3anjBFadDzhijME3QcX651yucne_irK_2JMS8HF5FuxNl85mE0nDrtn9Iq0z2gW69n00OrB970hpHTbYe0mAogZit; expires=Sat, 22-Jun-2013 08:21:37 GMT; path=/; domain=.google.com; HttpOnly' ], p3p: 'CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."', date: 'Fri, 21 Dec 2012 08:21:37 GMT', 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' } <HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"> <TITLE>302 Moved</TITLE></HEAD><BODY> <H1>302 Moved</H1> The document has moved <A HREF="https://www.google.com.tw/">here</A>. </BODY></HTML>

谷歌返回了一个302,告诉我们进行跳转,需要访问 https://www.google.com.tw/ 这个地址

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值