码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2017-07-12 17:48:29      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:blank   method   doc   tps   this   cti   type   info   ram   

有可能有这样的需求,需要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)

标签:blank   method   doc   tps   this   cti   type   info   ram   

原文地址:http://www.cnblogs.com/simadi/p/7156339.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!