request.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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: true
  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. else{
  198. //this.config.header['token'] = '';
  199. }
  200. const options = {};
  201. options.params = params;
  202. return this.request({
  203. url,
  204. sslVerify:false,
  205. method: 'GET',
  206. ...options
  207. });
  208. }
  209. post(url, data,isToken, options = {}) {
  210. console.log(isToken);
  211. if(isToken){
  212. this.config.header['token'] = uni.getStorageSync('token');
  213. }
  214. console.log(data);
  215. return this.request({
  216. url,
  217. data,
  218. method: 'POST',
  219. sslVerify:false,
  220. ...options
  221. });
  222. }
  223. // #ifndef MP-ALIPAY
  224. put(url, data, options = {}) {
  225. return this.request({
  226. url,
  227. data,
  228. method: 'PUT',
  229. ...options
  230. });
  231. }
  232. // #endif
  233. // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-BAIDU
  234. delete(url, data, options = {}) {
  235. return this.request({
  236. url,
  237. data,
  238. method: 'DELETE',
  239. ...options
  240. });
  241. }
  242. // #endif
  243. // #ifdef APP-PLUS || H5 || MP-WEIXIN
  244. connect(url, data, options = {}) {
  245. return this.request({
  246. url,
  247. data,
  248. method: 'CONNECT',
  249. ...options
  250. });
  251. }
  252. // #endif
  253. // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-BAIDU
  254. head(url, data, options = {}) {
  255. return this.request({
  256. url,
  257. data,
  258. method: 'HEAD',
  259. ...options
  260. });
  261. }
  262. // #endif
  263. // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-BAIDU
  264. options(url, data, options = {}) {
  265. return this.request({
  266. url,
  267. data,
  268. method: 'OPTIONS',
  269. ...options
  270. });
  271. }
  272. // #endif
  273. // #ifdef APP-PLUS || H5 || MP-WEIXIN
  274. trace(url, data, options = {}) {
  275. return this.request({
  276. url,
  277. data,
  278. method: 'TRACE',
  279. ...options
  280. });
  281. }
  282. // #endif
  283. upload(
  284. url,
  285. {
  286. // #ifdef APP-PLUS
  287. files,
  288. // #endif
  289. // #ifdef MP-ALIPAY
  290. fileType,
  291. // #endif
  292. filePath,
  293. name,
  294. header,
  295. formData = {},
  296. custom = {},
  297. params = {},
  298. getTask
  299. }
  300. ) {
  301. return new Promise((resolve, reject) => {
  302. let next = true;
  303. const globalHeader = {...this.config.header};
  304. delete globalHeader['content-type'];
  305. delete globalHeader['Content-Type'];
  306. const pubConfig = {
  307. baseUrl: this.config.baseUrl,
  308. url,
  309. // #ifdef MP-ALIPAY
  310. fileType,
  311. // #endif
  312. filePath,
  313. method: 'UPLOAD',
  314. name,
  315. header: header || globalHeader,
  316. formData,
  317. params,
  318. custom: {...this.config.custom, ...custom},
  319. getTask: getTask || this.config.getTask
  320. };
  321. // #ifdef APP-PLUS
  322. if (files) {
  323. pubConfig.files = files;
  324. }
  325. // #endif
  326. const cancel = (t = 'handle cancel', config = pubConfig) => {
  327. const err = {
  328. errMsg: t,
  329. config: config
  330. };
  331. reject(err);
  332. next = false;
  333. };
  334. const handleRe = {...this.requestBeforeFun(pubConfig, cancel)};
  335. const _config = {
  336. url: Request.mergeUrl(handleRe.url, handleRe.baseUrl, handleRe.params),
  337. // #ifdef MP-ALIPAY
  338. fileType: handleRe.fileType,
  339. // #endif
  340. filePath: handleRe.filePath,
  341. name: handleRe.name,
  342. header: handleRe.header,
  343. formData: handleRe.formData,
  344. complete: response => {
  345. response.config = handleRe;
  346. if (typeof response.data === 'string') {
  347. response.data = JSON.parse(response.data);
  348. }
  349. if (this.validateStatus(response.statusCode)) {
  350. // 成功
  351. response = this.requestComFun(response);
  352. resolve(response);
  353. } else {
  354. response = this.requestComFail(response);
  355. reject(response);
  356. }
  357. }
  358. };
  359. // #ifdef APP-PLUS
  360. if (handleRe.files) {
  361. _config.files = handleRe.files;
  362. }
  363. // #endif
  364. if (!next) return;
  365. const requestTask = uni.uploadFile(_config);
  366. if (handleRe.getTask) {
  367. handleRe.getTask(requestTask, handleRe);
  368. }
  369. });
  370. }
  371. download(url, options = {}) {
  372. return new Promise((resolve, reject) => {
  373. let next = true;
  374. const pubConfig = {
  375. baseUrl: this.config.baseUrl,
  376. url,
  377. method: 'DOWNLOAD',
  378. header: options.header || this.config.header,
  379. params: options.params || {},
  380. custom: {...this.config.custom, ...(options.custom || {})},
  381. getTask: options.getTask || this.config.getTask
  382. };
  383. const cancel = (t = 'handle cancel', config = pubConfig) => {
  384. const err = {
  385. errMsg: t,
  386. config: config
  387. };
  388. reject(err);
  389. next = false;
  390. };
  391. const handleRe = {...this.requestBeforeFun(pubConfig, cancel)};
  392. if (!next) return;
  393. const requestTask = uni.downloadFile({
  394. url: Request.mergeUrl(handleRe.url, handleRe.baseUrl, handleRe.params),
  395. header: handleRe.header,
  396. complete: response => {
  397. response.config = handleRe;
  398. if (this.validateStatus(response.statusCode)) {
  399. // 成功
  400. response = this.requestComFun(response);
  401. resolve(response);
  402. } else {
  403. response = this.requestComFail(response);
  404. reject(response);
  405. }
  406. }
  407. });
  408. if (handleRe.getTask) {
  409. handleRe.getTask(requestTask, handleRe);
  410. }
  411. });
  412. }
  413. }
  414. /**
  415. * setConfig回调
  416. * @return {Object} - 返回操作后的config
  417. * @callback Request~setConfigCallback
  418. * @param {Object} config - 全局默认config
  419. */
  420. /**
  421. * 请求拦截器回调
  422. * @return {Object} - 返回操作后的config
  423. * @callback Request~requestCallback
  424. * @param {Object} config - 全局config
  425. * @param {Function} [cancel] - 取消请求钩子,调用会取消本次请求
  426. */
  427. /**
  428. * 响应拦截器回调
  429. * @return {Object} - 返回操作后的response
  430. * @callback Request~responseCallback
  431. * @param {Object} response - 请求结果 response
  432. */
  433. /**
  434. * 响应错误拦截器回调
  435. * @return {Object} - 返回操作后的response
  436. * @callback Request~responseErrCallback
  437. * @param {Object} response - 请求结果 response
  438. */