request1.js 11 KB

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