request.js 11 KB

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