request.js 3.8 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
/**
 * 请求任务类
 */
class RequestTask {
  _xhr
  constructor (xhr) {
    this._xhr = xhr
  }
  abort () {
    if (this._xhr) {
      this._xhr.abort()
      delete this._xhr
    }
  }
}

/**
 * 解析响应头
 * @param {string} headers
 * @return {object}
 */
function parseHeaders (headers) {
  var headersObject = {}
  var headersArray = headers.split('\n')
  headersArray.forEach(header => {
    var find = header.match(/(\S+\s*):\s*(.*)/)
    if (!find || find.length !== 3) {
      return
    }
    var key = find[1]
    var val = find[2]
    headersObject[key] = val
  })
  return headersObject
}
/**
 * 发起网络请求
 * @param {object} param0
 * @param {string} callbackId
 * @return {RequestTask}
 */
export function request ({
  url,
  data,
  header,
  method,
  dataType,
  responseType
}, callbackId) {
  const {
    invokeCallbackHandler: invoke
  } = UniServiceJSBridge
  var body = null
  var timeout = (__uniConfig.networkTimeout && __uniConfig.networkTimeout.request) || 60 * 1000
  // 根据请求类型处理数据
  var contentType
  for (const key in header) {
    if (header.hasOwnProperty(key)) {
      if (key.toLowerCase() === 'content-type') {
        contentType = header[key]
        if (contentType.indexOf('application/json') === 0) {
          contentType = 'json'
        } else if (contentType.indexOf('application/x-www-form-urlencoded') === 0) {
          contentType = 'urlencoded'
        } else {
          contentType = 'string'
        }
        break
      }
    }
  }
  if (method !== 'GET') {
    if (!contentType) {
      /**
       * 跨域时部分服务器OPTION响应头Access-Control-Allow-Headers未包含Content-Type会请求失败
       */
      header['Content-Type'] = 'application/json'
      contentType = 'json'
    }
    if (typeof data === 'string' || data instanceof ArrayBuffer) {
      body = data
    } else {
      if (contentType === 'json') {
        try {
          body = JSON.stringify(data)
        } catch (error) {
          body = data.toString()
        }
      } else if (contentType === 'urlencoded') {
        let bodyArray = []
        for (let key in data) {
          if (data.hasOwnProperty(key)) {
            bodyArray.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
          }
        }
        body = bodyArray.join('&')
      } else {
        body = data.toString()
      }
    }
  }
  var xhr = new XMLHttpRequest()
  var requestTask = new RequestTask(xhr)
  xhr.open(method, url)
  for (var key in header) {
    if (header.hasOwnProperty(key)) {
      xhr.setRequestHeader(key, header[key])
    }
  }

  var timer = setTimeout(function () {
    xhr.onload = xhr.onabort = xhr.onerror = null
    requestTask.abort()
    invoke(callbackId, {
      errMsg: 'request:fail timeout'
    })
  }, timeout)
  xhr.responseType = responseType.toLowerCase()
  xhr.onload = function () {
    clearTimeout(timer)
    let statusCode = xhr.status
    let res = responseType === 'TEXT' ? xhr.responseText : xhr.response
    if (responseType === 'TEXT' && dataType === 'JSON') {
      try {
        res = JSON.parse(res)
      } catch (error) {
        // 和微信一致解析失败不抛出错误
        // invoke(callbackId, {
        //   errMsg: 'request:fail json parse error'
        // })
        // return
      }
    }
    invoke(callbackId, {
      data: res,
      statusCode,
      header: parseHeaders(xhr.getAllResponseHeaders()),
      errMsg: 'request:ok'
    })
  }
  xhr.onabort = function () {
    clearTimeout(timer)
    invoke(callbackId, {
      errMsg: 'request:fail abort'
    })
  }
  xhr.onerror = function () {
    clearTimeout(timer)
    invoke(callbackId, {
      errMsg: 'request:fail'
    })
  }
  xhr.send(body)
  return requestTask
fxy060608's avatar
fxy060608 已提交
155
}