代码展示

  1. /**
  2. * Request 1.0.6
  3. * @Class Request
  4. * @description luch-request 1.0.6 http请求插件
  5. * @Author lu-ch
  6. * @Date 2020-03-17
  7. * @Email webwork.s@qq.com
  8. * http://ext.dcloud.net.cn/plugin?id=392
  9. */
  10. export default class Request {
  11. config = {
  12. baseUrl: '',
  13. header: {
  14. 'content-type': 'application/json'
  15. },
  16. method: 'GET',
  17. dataType: 'json',
  18. // #ifndef MP-ALIPAY || APP-PLUS
  19. responseType: 'text',
  20. // #endif
  21. custom: {},
  22. // #ifdef MP-ALIPAY
  23. timeout: 30000,
  24. // #endif
  25. // #ifdef APP-PLUS
  26. sslVerify: true
  27. // #endif
  28. };
  29. static posUrl(url) {
  30. /* 判断url是否为绝对路径 */
  31. return /(http|https):\/\/([\w.]+\/?)\S*/.test(url);
  32. }
  33. static mergeUrl(url, baseUrl, params) {
  34. let mergeUrl = Request.posUrl(url) ? url : `${baseUrl}${url}`;
  35. if (Object.keys(params).length !== 0) {
  36. const paramsH = Request.addQueryString(params);
  37. mergeUrl += mergeUrl.includes('?') ? `&${paramsH}` : `?${paramsH}`;
  38. }
  39. return mergeUrl;
  40. }
  41. static addQueryString(params) {
  42. let paramsData = '';
  43. Object.keys(params).forEach(function(key) {
  44. paramsData += key + '=' + encodeURIComponent(params[key]) + '&';
  45. });
  46. return paramsData.substring(0, paramsData.length - 1);
  47. }
  48. /**
  49. * @property {Function} request 请求拦截器
  50. * @property {Function} response 响应拦截器
  51. * @type {{request: Request.interceptor.request, response: Request.interceptor.response}}
  52. */
  53. interceptor = {
  54. /**
  55. * @param {Request~requestCallback} cb - 请求之前拦截,接收一个函数(config, cancel)=> {return config}。第一个参数为全局config,第二个参数为函数,调用则取消本次请求。
  56. */
  57. request: cb => {
  58. if (cb) {
  59. this.requestBeforeFun = cb;
  60. }
  61. },
  62. /**
  63. * @param {Request~responseCallback} cb 响应拦截器,对响应数据做点什么
  64. * @param {Request~responseErrCallback} ecb 响应拦截器,对响应错误做点什么
  65. */
  66. response: (cb, ecb) => {
  67. if (cb) {
  68. this.requestComFun = cb;
  69. }
  70. if (ecb) {
  71. this.requestComFail = ecb;
  72. }
  73. }
  74. };
  75. requestBeforeFun(config) {
  76. return config;
  77. }
  78. requestComFun(response) {
  79. return response;
  80. }
  81. requestComFail(response) {
  82. return response;
  83. }
  84. /**
  85. * 自定义验证器,如果返回true 则进入响应拦截器的响应成功函数(resolve),否则进入响应拦截器的响应错误函数(reject)
  86. * @param { Number } statusCode - 请求响应体statusCode(只读)
  87. * @return { Boolean } 如果为true,则 resolve, 否则 reject
  88. */
  89. validateStatus(statusCode) {
  90. return statusCode === 200;
  91. }
  92. /**
  93. * @Function
  94. * @param {Request~setConfigCallback} f - 设置全局默认配置
  95. */
  96. setConfig(f) {
  97. this.config = f(this.config);
  98. }
  99. /**
  100. * @Function
  101. * @param {Object} options - 请求配置项
  102. * @prop {String} options.url - 请求路径
  103. * @prop {Object} options.data - 请求参数
  104. * @prop {Object} [options.responseType = config.responseType] [text|arraybuffer] - 响应的数据类型
  105. * @prop {Object} [options.dataType = config.dataType] - 如果设为 json,会尝试对返回的数据做一次 JSON.parse
  106. * @prop {Object} [options.header = config.header] - 请求header
  107. * @prop {Object} [options.method = config.method] - 请求方法
  108. * @returns {Promise<unknown>}
  109. */
  110. async request(options = {}) {
  111. options.baseUrl = this.config.baseUrl;
  112. options.dataType = options.dataType || this.config.dataType;
  113. // #ifndef MP-ALIPAY || APP-PLUS
  114. options.responseType = options.responseType || this.config.responseType;
  115. // #endif
  116. // #ifdef MP-ALIPAY
  117. options.timeout = options.timeout || this.config.timeout;
  118. // #endif
  119. options.url = options.url || '';
  120. options.data = options.data || {};
  121. options.params = options.params || {};
  122. options.header = options.header || this.config.header;
  123. options.method = options.method || this.config.method;
  124. options.custom = { ...this.config.custom, ...(options.custom || {}) };
  125. // #ifdef APP-PLUS
  126. options.sslVerify =
  127. options.sslVerify === undefined
  128. ? this.config.sslVerify
  129. : options.sslVerify;
  130. // #endif
  131. options.getTask = options.getTask || this.config.getTask;
  132. return new Promise((resolve, reject) => {
  133. let next = true;
  134. const cancel = (t = 'handle cancel', config = options) => {
  135. const err = {
  136. errMsg: t,
  137. config: config
  138. };
  139. reject(err);
  140. next = false;
  141. };
  142. const handleRe = { ...this.requestBeforeFun(options, cancel) };
  143. const _config = { ...handleRe };
  144. if (!next) return;
  145. const requestTask = uni.request({
  146. url: Request.mergeUrl(_config.url, _config.baseUrl, _config.params),
  147. data: _config.data,
  148. header: _config.header,
  149. method: _config.method,
  150. // #ifdef MP-ALIPAY
  151. timeout: _config.timeout,
  152. // #endif
  153. dataType: _config.dataType,
  154. // #ifndef MP-ALIPAY || APP-PLUS
  155. responseType: _config.responseType,
  156. // #endif
  157. // #ifdef APP-PLUS
  158. sslVerify: _config.sslVerify,
  159. // #endif
  160. complete: response => {
  161. response.config = handleRe;
  162. if (this.validateStatus(response.statusCode)) {
  163. // 成功
  164. response = this.requestComFun(response);
  165. resolve(response);
  166. } else {
  167. response = this.requestComFail(response);
  168. reject(response);
  169. }
  170. }
  171. });
  172. if (handleRe.getTask) {
  173. handleRe.getTask(requestTask, handleRe);
  174. }
  175. });
  176. }
  177. get(url, params = {}) {
  178. const options = {};
  179. options.params = params;
  180. return this.request({
  181. url,
  182. method: 'GET',
  183. ...options
  184. });
  185. }
  186. post(url, data, options = {}) {
  187. return this.request({
  188. url,
  189. data,
  190. method: 'POST',
  191. ...options
  192. });
  193. }
  194. // #ifndef MP-ALIPAY
  195. put(url, data, options = {}) {
  196. return this.request({
  197. url,
  198. data,
  199. method: 'PUT',
  200. ...options
  201. });
  202. }
  203. // #endif
  204. // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-BAIDU
  205. delete(url, data, options = {}) {
  206. return this.request({
  207. url,
  208. data,
  209. method: 'DELETE',
  210. ...options
  211. });
  212. }
  213. // #endif
  214. // #ifdef APP-PLUS || H5 || MP-WEIXIN
  215. connect(url, data, options = {}) {
  216. return this.request({
  217. url,
  218. data,
  219. method: 'CONNECT',
  220. ...options
  221. });
  222. }
  223. // #endif
  224. // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-BAIDU
  225. head(url, data, options = {}) {
  226. return this.request({
  227. url,
  228. data,
  229. method: 'HEAD',
  230. ...options
  231. });
  232. }
  233. // #endif
  234. // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-BAIDU
  235. options(url, data, options = {}) {
  236. return this.request({
  237. url,
  238. data,
  239. method: 'OPTIONS',
  240. ...options
  241. });
  242. }
  243. // #endif
  244. // #ifdef APP-PLUS || H5 || MP-WEIXIN
  245. trace(url, data, options = {}) {
  246. return this.request({
  247. url,
  248. data,
  249. method: 'TRACE',
  250. ...options
  251. });
  252. }
  253. // #endif
  254. upload(
  255. url,
  256. {
  257. // #ifdef APP-PLUS
  258. files,
  259. // #endif
  260. // #ifdef MP-ALIPAY
  261. fileType,
  262. // #endif
  263. filePath,
  264. name,
  265. header,
  266. formData = {},
  267. custom = {},
  268. params = {},
  269. getTask
  270. }
  271. ) {
  272. return new Promise((resolve, reject) => {
  273. let next = true;
  274. const globalHeader = { ...this.config.header };
  275. delete globalHeader['content-type'];
  276. delete globalHeader['Content-Type'];
  277. const pubConfig = {
  278. baseUrl: this.config.baseUrl,
  279. url,
  280. // #ifdef MP-ALIPAY
  281. fileType,
  282. // #endif
  283. filePath,
  284. method: 'UPLOAD',
  285. name,
  286. header: header || globalHeader,
  287. formData,
  288. params,
  289. custom: { ...this.config.custom, ...custom },
  290. getTask: getTask || this.config.getTask
  291. };
  292. // #ifdef APP-PLUS
  293. if (files) {
  294. pubConfig.files = files;
  295. }
  296. // #endif
  297. const cancel = (t = 'handle cancel', config = pubConfig) => {
  298. const err = {
  299. errMsg: t,
  300. config: config
  301. };
  302. reject(err);
  303. next = false;
  304. };
  305. const handleRe = { ...this.requestBeforeFun(pubConfig, cancel) };
  306. const _config = {
  307. url: Request.mergeUrl(handleRe.url, handleRe.baseUrl, handleRe.params),
  308. // #ifdef MP-ALIPAY
  309. fileType: handleRe.fileType,
  310. // #endif
  311. filePath: handleRe.filePath,
  312. name: handleRe.name,
  313. header: handleRe.header,
  314. formData: handleRe.formData,
  315. complete: response => {
  316. response.config = handleRe;
  317. if (typeof response.data === 'string') {
  318. response.data = JSON.parse(response.data);
  319. }
  320. if (this.validateStatus(response.statusCode)) {
  321. // 成功
  322. response = this.requestComFun(response);
  323. resolve(response);
  324. } else {
  325. response = this.requestComFail(response);
  326. reject(response);
  327. }
  328. }
  329. };
  330. // #ifdef APP-PLUS
  331. if (handleRe.files) {
  332. _config.files = handleRe.files;
  333. }
  334. // #endif
  335. if (!next) return;
  336. const requestTask = uni.uploadFile(_config);
  337. if (handleRe.getTask) {
  338. handleRe.getTask(requestTask, handleRe);
  339. }
  340. });
  341. }
  342. download(url, options = {}) {
  343. return new Promise((resolve, reject) => {
  344. let next = true;
  345. const pubConfig = {
  346. baseUrl: this.config.baseUrl,
  347. url,
  348. method: 'DOWNLOAD',
  349. header: options.header || this.config.header,
  350. params: options.params || {},
  351. custom: { ...this.config.custom, ...(options.custom || {}) },
  352. getTask: options.getTask || this.config.getTask
  353. };
  354. const cancel = (t = 'handle cancel', config = pubConfig) => {
  355. const err = {
  356. errMsg: t,
  357. config: config
  358. };
  359. reject(err);
  360. next = false;
  361. };
  362. const handleRe = { ...this.requestBeforeFun(pubConfig, cancel) };
  363. if (!next) return;
  364. const requestTask = uni.downloadFile({
  365. url: Request.mergeUrl(handleRe.url, handleRe.baseUrl, handleRe.params),
  366. header: handleRe.header,
  367. complete: response => {
  368. response.config = handleRe;
  369. if (this.validateStatus(response.statusCode)) {
  370. // 成功
  371. response = this.requestComFun(response);
  372. resolve(response);
  373. } else {
  374. response = this.requestComFail(response);
  375. reject(response);
  376. }
  377. }
  378. });
  379. if (handleRe.getTask) {
  380. handleRe.getTask(requestTask, handleRe);
  381. }
  382. });
  383. }
  384. }
  385. /**
  386. * setConfig回调
  387. * @return {Object} - 返回操作后的config
  388. * @callback Request~setConfigCallback
  389. * @param {Object} config - 全局默认config
  390. */
  391. /**
  392. * 请求拦截器回调
  393. * @return {Object} - 返回操作后的config
  394. * @callback Request~requestCallback
  395. * @param {Object} config - 全局config
  396. * @param {Function} [cancel] - 取消请求钩子,调用会取消本次请求
  397. */
  398. /**
  399. * 响应拦截器回调
  400. * @return {Object} - 返回操作后的response
  401. * @callback Request~responseCallback
  402. * @param {Object} response - 请求结果 response
  403. */
  404. /**
  405. * 响应错误拦截器回调
  406. * @return {Object} - 返回操作后的response
  407. * @callback Request~responseErrCallback
  408. * @param {Object} response - 请求结果 response
  409. */