request.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. /**
  2. * version 1.1.7
  3. */
  4. class Request {
  5. constructor(config = {}) {
  6. this.config = {};
  7. this.config.baseUrl = config.baseUrl? config.baseUrl: '';
  8. this.config.dataType = config.dataType? config.dataType: 'json';
  9. this.config.responseType = config.responseType? config.responseType: 'text';
  10. this.config.header = config.header? config.header: {};
  11. this.reqInterceptors = null;
  12. this.resInterceptors = null;
  13. this.interceptors = {
  14. request: fn => {
  15. this.reqInterceptors = fn;
  16. },
  17. response: fn => {
  18. this.resInterceptors = fn;
  19. }
  20. }
  21. }
  22. async get(url, config = {}) {
  23. return this._request('get', url, config);
  24. }
  25. async post(url, config = {}) {
  26. return this._request('post', url, config);
  27. }
  28. async put(url, config = {}) {
  29. return this._request('put', url, config);
  30. }
  31. async delete(url, config = {}) {
  32. return this._request('delete', url, config);
  33. }
  34. setConfig(config = {}) {
  35. this.config = this._deepCopy(this._merge(this.config, config));
  36. }
  37. getConfig() {
  38. return this.config;
  39. }
  40. _request(method, url, config) {
  41. const _this = this;
  42. let newConfig = this._deepCopy(this._merge(this.config, config));
  43. let lastConfig = {};
  44. if (this.reqInterceptors && typeof this.reqInterceptors === 'function') {
  45. let reqInterceptors = this.reqInterceptors(newConfig);
  46. if (!reqInterceptors && process.env.NODE_ENV === "development") {
  47. console.warn('请求被拦截,此消息仅在开发环境显示。')
  48. return false;
  49. } else if (Object.prototype.toString.call(reqInterceptors) === "[object Promise]") {
  50. return reqInterceptors;
  51. }
  52. lastConfig = this._deepCopy(reqInterceptors);
  53. } else {
  54. lastConfig = this._deepCopy(newConfig);
  55. }
  56. let fullUrl = this._formatUrl(lastConfig.baseUrl, url);
  57. return new Promise((resolve, reject) => {
  58. let requestTask= uni.request({
  59. url: fullUrl,
  60. method:method,
  61. crossDomain :true,
  62. data: lastConfig.data? lastConfig.data: {},
  63. header: lastConfig.header,
  64. dataType: lastConfig.dataType,
  65. responseType: lastConfig.responseType,
  66. fail:function(e){
  67. requestTask.abort();
  68. uni.showToast({
  69. icon:"none",
  70. duration:2000,
  71. title:e.errMsg
  72. })
  73. },
  74. complete: function (status) { //当请求完成时调用函数
  75. if (status == 'timeout') {//status == 'timeout'意为超时,status的可能取值:success,notmodified,nocontent,error,timeout,abort,parsererror
  76. requestTask.abort(); //取消请求
  77. uni.showToast({
  78. icon:"none",
  79. duration:2000,
  80. title:'网络不稳定,请求超时'
  81. })
  82. }
  83. },
  84. async complete(response) {
  85. let res = response;
  86. if (_this.resInterceptors && typeof _this.resInterceptors === 'function') {
  87. let resInterceptors = _this.resInterceptors(res);
  88. if (!resInterceptors) {
  89. reject('返回值已被您拦截!');
  90. return;
  91. } else if (Object.prototype.toString.call(resInterceptors) === "[object Promise]") {
  92. try {
  93. let promiseRes = await resInterceptors;
  94. resolve(promiseRes)
  95. } catch (error) {
  96. reject(error)
  97. }
  98. } else {
  99. res = resInterceptors;
  100. }
  101. }
  102. resolve(res);
  103. }
  104. });
  105. })
  106. }
  107. _formatUrl(baseUrl, url) {
  108. if (!baseUrl) return url;
  109. let formatUrl = '';
  110. const baseUrlEndsWithSlash = baseUrl.endsWith('/');
  111. const urlStartsWithSlash = url.startsWith('/');
  112. if (baseUrlEndsWithSlash && urlStartsWithSlash) {
  113. formatUrl = baseUrl + url.substring(1);
  114. } else if (baseUrlEndsWithSlash || urlStartsWithSlash) {
  115. formatUrl = baseUrl + url;
  116. } else {
  117. formatUrl = baseUrl + '/' + url;
  118. }
  119. return formatUrl;
  120. }
  121. _merge(oldConfig, newConfig) {
  122. let mergeConfig = this._deepCopy(oldConfig);
  123. if (!newConfig || !Object.keys(newConfig).length) return mergeConfig;
  124. for (let key in newConfig) {
  125. if (key !== 'header') {
  126. mergeConfig[key] = newConfig[key];
  127. } else {
  128. if (Object.prototype.toString.call(newConfig[key]) === '[object Object]') {
  129. for (let headerKey in newConfig[key]) {
  130. mergeConfig[key][headerKey] = newConfig[key][headerKey];
  131. }
  132. }
  133. }
  134. }
  135. return mergeConfig;
  136. }
  137. _deepCopy(obj) {
  138. let result = Array.isArray(obj) ? [] : {};
  139. for (let key in obj) {
  140. if (obj.hasOwnProperty(key)) {
  141. if (typeof obj[key] === 'object') {
  142. result[key] = this._deepCopy(obj[key]);
  143. } else {
  144. result[key] = obj[key];
  145. }
  146. }
  147. }
  148. return result;
  149. }
  150. }
  151. if (!global.$request) {
  152. global.$request = new Request();
  153. }
  154. export default global.$request;