Typescript/NodeJS Proxy HTTP Request使用代理发起http请求工具类,修改代理IP和端口配置即可使用

使用示范

  • get
import { ProxyHttpUtil } from '../../utils/ProxyHttpUtil';
let ret  = await ProxyHttpUtil.get('https://xxxx.com/api/v2/summary.json')
console.log(ret);
  • post
import { ProxyHttpUtil } from '../../utils/ProxyHttpUtil';
let ret  = await ProxyHttpUtil.post('https://xxxx.com/xxxx',{"msg":"hello"})
console.log(ret);

依赖库

其他细节可上npm网站里去查这两个库的使用

  • got
# npm 
npm install got
# or yarn
yarn add got
  • tunnel
# npm 
npm install tunnel
# or yarn
yarn add tunnel

工具类代码

import { Const } from '../const';

/**
 * first step: add dependencies
 * shell:
 * npm install got
 * npm install tunnel
 * second step: config proxy host and port
 *
 * author: humorchen
 * email: 3301533914@qq.com
 */
const got = require('got');
const tunnel = require('tunnel');
export class ProxyHttpUtil {
  /**
   * proxy ip need modify
   */
  static ProxyIp  = 'your proxy server ip'
  /**
   * proxy port need modify
   */
  static ProxyPort  = 3128

  /**
   * get method
   * @param url
   */
  static async get(url):Promise<object>{
    let ret = await got(url, {
      agent: {
        https: tunnel.httpsOverHttp({
          proxy: {
            host: this.ProxyIp,
            port: this.ProxyPort
          }
        })
      },
      responseType: 'json'
    });
    return ret.body
  }

  /**
   * post method
   * @param url
   * @param json
   */
  static async post(url,json?:object):Promise<object>{
    let ret = await got(url, {
      agent: {
        https: tunnel.httpsOverHttp({
          proxy: {
            host: this.ProxyIp,
            port: this.ProxyPort
          }
        })
      },
      json: json,
      responseType: 'json'
    });
    return ret.body
  }


}
posted @ 2021-06-08 15:46  HumorChen99  阅读(5)  评论(0编辑  收藏  举报  来源