nodejs通过代理,proxy发送http请求

有可能有这样的需求,需要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=,
     'N ],
  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/ 这个地址