zoukankan      html  css  js  c++  java
  • 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/ 这个地址

  • 相关阅读:
    [HNOI2002]营业额统计
    HDU 1374
    HDU 3345
    HDU 2089
    Graham扫描法
    Codeforces 1144D Deduction Queries 并查集
    Codeforces 916E Jamie and Tree 线段树
    Codeforces 1167F Scalar Queries 树状数组
    Codeforces 1167E Range Deleting
    Codeforces 749E Inversions After Shuffle 树状数组 + 数学期望
  • 原文地址:https://www.cnblogs.com/simadi/p/7156339.html
Copyright © 2011-2022 走看看