anyproxy4.0HTTP代理服务器
AnyProxy是一个开放式的HTTP代理服务器。
Github主页:https://github.com/alibaba/anyproxy
本文主要讲解anyproxy 如何作为npm模块整合进其他工具
引入
npm i anyproxy --save
const AnyProxy = require('anyproxy');
const options = {
  port: 8001,
  rule: require('./ruleModule.js'),
  webInterface: {
    enable: true,
    webPort: 8002
  },
  // throttle: 10000,
  forceProxyHttps: false,
  wsIntercept: false, // 不开启websocket代理
  silent: false,
  dangerouslyIgnoreUnauthorized: true
};
const proxyServer = new AnyProxy.ProxyServer(options);
proxyServer.on('ready', () => { /* */ });
proxyServer.on('error', (e) => { /* */ });
proxyServer.start();
//when finished
// proxyServer.close();
options
- port {number} 必选,代理服务器端口
 - rule {object} 自定义规则模块
 - throttle {number} 限速值,单位kb/s,默认不限速
 - forceProxyHttps {boolean} 是否强制拦截所有的https,忽略规则模块的返回,默认false
 - silent {boolean} 是否屏蔽所有console输出,默认false
 - dangerouslyIgnoreUnauthorized {boolean} 是否忽略请求中的证书错误,默认false
 - wsIntercept {boolean} 是否开启websocket代理,默认false
 - webInterface {object} web版界面配置
 - enable {boolean} 是否启用web版界面,默认false
 - webPort {number} web版界面端口号,默认8002
 
代理HTTPS
AnyProxy默认不对https请求做处理,如需看到明文信息,需要配置CA证书
解析https请求的原理是中间人攻击(man-in-the-middle),用户必须信任AnyProxy生成的CA证书,才能进行后续流程
生成证书并解析所有https请求
anyproxy-ca #生成rootCA证书,生成后需要手动信任
anyproxy --intercept #启动AnyProxy,并解析所有https请求
rule模块
ruleModule 实现将浏览器访问的指定域名的网站全部下载下来
const URL = require('./url.js')
module.exports = {
  // 模块介绍
  summary: 'my customized rule for AnyProxy',
  // 发送请求前拦截处理
  *beforeSendRequest(requestDetail) { /* ... */ },
  // 发送响应前处理
  *beforeSendResponse(requestDetail, responseDetail) { 
      const url = requestDetail.url;
      
      if(url.indexOf('baidu')!=-1){
          console.log(url);
          const data = responseDetail.response.body;
          console.log('data',url);
          // URL.downloadFile(url,data);
      }
  },
  // 是否处理https请求
  *beforeDealHttpsRequest(requestDetail) { 
      const host = requestDetail.host;
      if(host&&host.indexOf('baidu')!=-1){
          return true;
      }else{
        return false
      }
  },
  // 请求出错的事件
  *onError(requestDetail, error) { /* ... */ },
  // https连接服务器出错
  *onConnectError(requestDetail, error) { /* ... */ }
};
如需要完整代码,请留言