Node.JS 重发网络请求

本文探讨了在Node.js环境中如何处理网络请求失败的情况,并详细介绍了如何实现一个智能的请求重试机制,包括错误检测、延迟策略和最大重试次数控制,以提高应用的稳定性和可靠性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 重发网络请求
 * 
 * @example
 * new Request(raw).send((result) => {
 *   console.log(result);
 * })
 */
class Request {

  /**
   * constructor
   *
   * @param {string} raw 抓包得到的原始字符串
   */
  constructor(raw) {
    const http = require('http');
    var options = this.parseOptions(raw)
    this.req = http.request(options, (res) => {
      console.log('STATUS:' + res.statusCode);
      console.log('HEADERS:' + JSON.stringify(res.headers));
      res.setEncoding('utf-8')
      res.on('data', (chunk) => {
        if (this.success) {
          this.success(chunk)
        }
      })
    })

    this.req.on('error', (e) => {
      if (this.error) {
        this.error(e)
      }
      console.log('request error!!!');
      console.error(e);
    })

    if (options.method == 'POST') {
      this.req.write(options.content)
    }
  }

  /**
   * 发起网络请求
   *
   * @param {function} success 发送成功的回调方法
   * @param {function} error 发送失败的回调方法
   */
  send(success, error) {
    this.success = success
    this.error = error
    this.req.end()
  }

  parseOptions(raw) {
    const url = require('url');
    var lines = raw.split('\n')
    var firstLine = lines[0]
    var arr = firstLine.split(' ')
    var options = url.parse(arr[1])
    options.method = arr[0]
    options.headers = {}
    for (var i = 0; i < lines.length; i++) {
      if (lines[i].trim().length == 0) {
        options.content = lines.slice(i).join('\n').trim()
        break
      } else if (i != 0) {
        var line = lines[i].trim()
        var m = line.match(/^([^:]+):(.*)$/)
        options.headers[m[1].trim()] = m[2].trim()
      }
    }

    if (!options.host) {
      options.host = options.headers['Host']
    }

    delete options.headers['Host']
    delete options.headers['Content-Length']
    return options
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值