1. 程式人生 > >nodejs通過代理(proxy)發送http請求(request)

nodejs通過代理(proxy)發送http請求(request)

same pan response main only ext ejs https status

有可能有這樣的需求,需要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/ 這個地址

nodejs通過代理(proxy)發送http請求(request)