baseRequest.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /**
  2. * @(#)2019/11/14.
  3. * 封装底层请求,试图替代jq的请求
  4. * @author 足道
  5. * Copyright (c) 2019, YUNXI. All rights reserved.
  6. * YUNXI PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  7. */
  8. const jsonpParse = JSON.parse
  9. class XHR {
  10. constructor(url, headers, method) {
  11. this.url = url
  12. this.method = method
  13. this.headers = headers || {}
  14. this.xhr = new XMLHttpRequest()
  15. this.init()
  16. }
  17. /**
  18. * 这样就可以链式调用节约一行代码
  19. *
  20. * @static
  21. * @param {*} url
  22. * @param {*} header
  23. * @returns
  24. * @memberof XHR
  25. */
  26. static new(url, header) {
  27. return new this(url, header)
  28. }
  29. /**
  30. * 父类初始化
  31. *
  32. * @memberof XHR
  33. */
  34. init() {
  35. this.xhr.timeout = 8000
  36. this.xhr.open(this.method, this.url, true)
  37. Object.keys(this.headers).forEach((key) => {
  38. const val = this.headers[key]
  39. this.xhr.setRequestHeader(key, val)
  40. })
  41. }
  42. _send = (xhr, data) => {
  43. if (data == null) {
  44. xhr.send()
  45. } else {
  46. xhr.send(data)
  47. }
  48. }
  49. /**
  50. * 请求发送
  51. *
  52. * @param {Object} data
  53. * @returns
  54. */
  55. xhrSend(data, onprogress) {
  56. const { xhr } = this
  57. xhr.withCredentials = false
  58. return new Promise((resolve, reject) => {
  59. xhr.onreadystatechange = (event) => {
  60. const that = event.currentTarget
  61. const { status } = that
  62. if (that.readyState === 4) {
  63. if ([200, 204].includes(status)) {
  64. const { response } = that
  65. resolve(response.data)
  66. } else if (status === 403) {
  67. resolve({ status, message: '没有权限' })
  68. } else if (that.readyState === 4) {
  69. reject({ status, body: that })
  70. }
  71. }
  72. }
  73. xhr.onprogress = onprogress
  74. xhr.ontimeout = () => reject('请求超时')
  75. xhr.onerror = reject
  76. this._send(xhr, data)
  77. })
  78. }
  79. }
  80. class PostXhr extends XHR {
  81. constructor(url, headers) {
  82. super(url, headers, 'post')
  83. this.xhr.timeout = 100 * 1000
  84. }
  85. send(data) {
  86. this.xhrSend(data)
  87. }
  88. }
  89. class GetXhr extends XHR {
  90. constructor(url, headers) {
  91. super(url, headers, 'get')
  92. this.xhr.timeout = 100 * 1000
  93. this.xhr.responseType = 'json'
  94. }
  95. send(data) {
  96. return this.xhrSend(data)
  97. }
  98. }
  99. export { PostXhr, GetXhr }