Xhr.weapp.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. class XhrWeapp {
  7. constructor() {
  8. this.UNSENT = 0;
  9. this.OPENED = 1;
  10. this.HEADERS_RECEIVED = 2;
  11. this.LOADING = 3;
  12. this.DONE = 4;
  13. this.header = {};
  14. this.readyState = this.DONE;
  15. this.status = 0;
  16. this.response = '';
  17. this.responseType = '';
  18. this.responseText = '';
  19. this.responseHeader = {};
  20. this.method = '';
  21. this.url = '';
  22. this.onabort = () => {};
  23. this.onprogress = () => {};
  24. this.onerror = () => {};
  25. this.onreadystatechange = () => {};
  26. this.requestTask = null;
  27. }
  28. getAllResponseHeaders() {
  29. let header = '';
  30. for (const key in this.responseHeader) {
  31. header += key + ':' + this.getResponseHeader(key) + '\r\n';
  32. }
  33. return header;
  34. }
  35. getResponseHeader(key) {
  36. return this.responseHeader[key];
  37. }
  38. setRequestHeader(key, value) {
  39. this.header[key] = value;
  40. }
  41. open(method, url) {
  42. this.method = method;
  43. this.url = url;
  44. }
  45. abort() {
  46. if (!this.requestTask) {
  47. return;
  48. }
  49. this.requestTask.abort();
  50. this.status = 0;
  51. this.response = undefined;
  52. this.onabort();
  53. this.onreadystatechange();
  54. }
  55. send(data) {
  56. // @ts-ignore
  57. this.requestTask = wx.request({
  58. url: this.url,
  59. method: this.method,
  60. data: data,
  61. header: this.header,
  62. responseType: this.responseType,
  63. success: res => {
  64. this.status = res.statusCode;
  65. this.response = res.data;
  66. this.responseHeader = res.header;
  67. this.responseText = JSON.stringify(res.data);
  68. this.requestTask = null;
  69. this.onreadystatechange();
  70. },
  71. fail: err => {
  72. this.requestTask = null;
  73. // @ts-ignore
  74. this.onerror(err);
  75. }
  76. });
  77. this.requestTask.onProgressUpdate(res => {
  78. const event = {
  79. lengthComputable: res.totalBytesExpectedToWrite !== 0,
  80. loaded: res.totalBytesWritten,
  81. total: res.totalBytesExpectedToWrite
  82. };
  83. // @ts-ignore
  84. this.onprogress(event);
  85. });
  86. }
  87. }
  88. module.exports = XhrWeapp;
  89. var _default = exports.default = XhrWeapp;