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

來源:互聯網
上載者:User

標籤:blank   method   doc   tps   this   cti   type   info   ram   

有可能有這樣的需求,需要node作為web伺服器通過另外一台http/httpsProxy 伺服器發http或者https請求,廢話不多說直接上代碼大家都懂的:

var http = require(‘http‘)var opt = { host:‘這裡放Proxy 伺服器的ip或者網域名稱‘, port:‘這裡放Proxy 伺服器的連接埠號碼‘, 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();

這樣我們就通過了指定Proxy 伺服器發出了https的請求,注意這裡我們同Proxy 伺服器是http協議的,不是https,返回的結果當然肯定會根據你的Proxy 伺服器不同有所不同。

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>

Google返回了一個302,告訴我們進行跳轉,需要訪問 https://www.google.com.tw/ 這個地址

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.