request.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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: 10000,
  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. // return false
  112. options.baseUrl = this.config.baseUrl;
  113. options.dataType = options.dataType || this.config.dataType;
  114. // #ifndef MP-ALIPAY || APP-PLUS
  115. options.responseType = options.responseType || this.config.responseType;
  116. // #endif
  117. // #ifdef MP-ALIPAY
  118. options.timeout = options.timeout || this.config.timeout;
  119. // #endif
  120. options.url = options.url || '';
  121. options.data = options.data || {};
  122. options.params = options.params || {};
  123. options.header = options.header || this.config.header;
  124. options.method = options.method || this.config.method;
  125. options.custom = { ...this.config.custom, ...(options.custom || {}) };
  126. // #ifdef APP-PLUS
  127. options.sslVerify =
  128. options.sslVerify === undefined
  129. ? this.config.sslVerify
  130. : options.sslVerify;
  131. // #endif
  132. options.getTask = options.getTask || this.config.getTask;
  133. return new Promise((resolve, reject) => {
  134. let next = true;
  135. const cancel = (t = 'handle cancel', config = options) => {
  136. const err = {
  137. errMsg: t,
  138. config: config
  139. };
  140. reject(err);
  141. next = false;
  142. };
  143. const handleRe = { ...this.requestBeforeFun(options, cancel) };
  144. const _config = { ...handleRe };
  145. if (!next) return;
  146. const requestTask = uni.request({
  147. url: Request.mergeUrl(_config.url, _config.baseUrl, _config.params),
  148. data: _config.data,
  149. header: _config.header,
  150. method: _config.method,
  151. // #ifdef MP-ALIPAY
  152. timeout: _config.timeout,
  153. // #endif
  154. dataType: _config.dataType,
  155. // #ifndef MP-ALIPAY || APP-PLUS
  156. responseType: _config.responseType,
  157. // #endif
  158. // #ifdef APP-PLUS
  159. sslVerify: _config.sslVerify,
  160. // #endif
  161. complete: response => {
  162. response.config = handleRe;
  163. if (this.validateStatus(response.statusCode)) {
  164. // 成功
  165. response = this.requestComFun(response);
  166. resolve(response);
  167. } else {
  168. response = this.requestComFail(response);
  169. reject(response);
  170. }
  171. }
  172. });
  173. if (handleRe.getTask) {
  174. handleRe.getTask(requestTask, handleRe);
  175. }
  176. });
  177. }
  178. get(url, params = {},isToken) {
  179. return this.request({
  180. url,
  181. method: 'GET',
  182. params,
  183. isToken
  184. });
  185. }
  186. del(url,params={},isToken){
  187. return this.request({
  188. url,
  189. method:'delete',
  190. params,
  191. isToken
  192. })
  193. }
  194. post(url, data, options = {},isToken) {
  195. return this.request({
  196. url,
  197. data,
  198. method: 'POST',
  199. ...options,
  200. isToken
  201. });
  202. }
  203. // #ifndef MP-ALIPAY
  204. put(url, data, options = {},isToken) {
  205. return this.request({
  206. url,
  207. data,
  208. method: 'PUT',
  209. ...options,
  210. isToken
  211. });
  212. }
  213. // #endif
  214. // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-BAIDU
  215. delete(url, data, options = {},isToken) {
  216. return this.request({
  217. url,
  218. data,
  219. method: 'DELETE',
  220. ...options,
  221. isToken
  222. });
  223. }
  224. // #endif
  225. // #ifdef APP-PLUS || H5 || MP-WEIXIN
  226. connect(url, data, options = {}) {
  227. return this.request({
  228. url,
  229. data,
  230. method: 'CONNECT',
  231. ...options
  232. });
  233. }
  234. // #endif
  235. // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-BAIDU
  236. head(url, data, options = {}) {
  237. return this.request({
  238. url,
  239. data,
  240. method: 'HEAD',
  241. ...options
  242. });
  243. }
  244. // #endif
  245. // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-BAIDU
  246. options(url, data, options = {}) {
  247. return this.request({
  248. url,
  249. data,
  250. method: 'OPTIONS',
  251. ...options
  252. });
  253. }
  254. // #endif
  255. // #ifdef APP-PLUS || H5 || MP-WEIXIN
  256. trace(url, data, options = {}) {
  257. return this.request({
  258. url,
  259. data,
  260. method: 'TRACE',
  261. ...options
  262. });
  263. }
  264. // #endif
  265. upload(
  266. url,
  267. {
  268. // #ifdef APP-PLUS
  269. files,
  270. // #endif
  271. // #ifdef MP-ALIPAY
  272. fileType,
  273. // #endif
  274. filePath,
  275. name,
  276. header,
  277. formData = {},
  278. custom = {},
  279. params = {},
  280. getTask
  281. }
  282. ) {
  283. return new Promise((resolve, reject) => {
  284. let next = true;
  285. const globalHeader = { ...this.config.header };
  286. delete globalHeader['content-type'];
  287. delete globalHeader['Content-Type'];
  288. const pubConfig = {
  289. baseUrl: this.config.baseUrl,
  290. url,
  291. // #ifdef MP-ALIPAY
  292. fileType,
  293. // #endif
  294. filePath,
  295. method: 'UPLOAD',
  296. name,
  297. header: header || globalHeader,
  298. formData,
  299. params,
  300. custom: { ...this.config.custom, ...custom },
  301. getTask: getTask || this.config.getTask
  302. };
  303. // #ifdef APP-PLUS
  304. if (files) {
  305. pubConfig.files = files;
  306. }
  307. // #endif
  308. const cancel = (t = 'handle cancel', config = pubConfig) => {
  309. const err = {
  310. errMsg: t,
  311. config: config
  312. };
  313. reject(err);
  314. next = false;
  315. };
  316. const handleRe = { ...this.requestBeforeFun(pubConfig, cancel) };
  317. const _config = {
  318. url: Request.mergeUrl(handleRe.url, handleRe.baseUrl, handleRe.params),
  319. // #ifdef MP-ALIPAY
  320. fileType: handleRe.fileType,
  321. // #endif
  322. filePath: handleRe.filePath,
  323. name: handleRe.name,
  324. header: handleRe.header,
  325. formData: handleRe.formData,
  326. complete: response => {
  327. response.config = handleRe;
  328. if (typeof response.data === 'string') {
  329. response.data = JSON.parse(response.data);
  330. }
  331. if (this.validateStatus(response.statusCode)) {
  332. // 成功
  333. response = this.requestComFun(response);
  334. resolve(response);
  335. } else {
  336. response = this.requestComFail(response);
  337. reject(response);
  338. }
  339. }
  340. };
  341. // #ifdef APP-PLUS
  342. if (handleRe.files) {
  343. _config.files = handleRe.files;
  344. }
  345. // #endif
  346. if (!next) return;
  347. const requestTask = uni.uploadFile(_config);
  348. if (handleRe.getTask) {
  349. handleRe.getTask(requestTask, handleRe);
  350. }
  351. });
  352. }
  353. download(url, options = {}) {
  354. return new Promise((resolve, reject) => {
  355. let next = true;
  356. const pubConfig = {
  357. baseUrl: this.config.baseUrl,
  358. url,
  359. method: 'DOWNLOAD',
  360. header: options.header || this.config.header,
  361. params: options.params || {},
  362. custom: { ...this.config.custom, ...(options.custom || {}) },
  363. getTask: options.getTask || this.config.getTask
  364. };
  365. const cancel = (t = 'handle cancel', config = pubConfig) => {
  366. const err = {
  367. errMsg: t,
  368. config: config
  369. };
  370. reject(err);
  371. next = false;
  372. };
  373. const handleRe = { ...this.requestBeforeFun(pubConfig, cancel) };
  374. if (!next) return;
  375. const requestTask = uni.downloadFile({
  376. url: Request.mergeUrl(handleRe.url, handleRe.baseUrl, handleRe.params),
  377. header: handleRe.header,
  378. complete: response => {
  379. response.config = handleRe;
  380. if (this.validateStatus(response.statusCode)) {
  381. // 成功
  382. response = this.requestComFun(response);
  383. resolve(response);
  384. } else {
  385. response = this.requestComFail(response);
  386. reject(response);
  387. }
  388. }
  389. });
  390. if (handleRe.getTask) {
  391. handleRe.getTask(requestTask, handleRe);
  392. }
  393. });
  394. }
  395. }
  396. /**
  397. * setConfig回调
  398. * @return {Object} - 返回操作后的config
  399. * @callback Request~setConfigCallback
  400. * @param {Object} config - 全局默认config
  401. */
  402. /**
  403. * 请求拦截器回调
  404. * @return {Object} - 返回操作后的config
  405. * @callback Request~requestCallback
  406. * @param {Object} config - 全局config
  407. * @param {Function} [cancel] - 取消请求钩子,调用会取消本次请求
  408. */
  409. /**
  410. * 响应拦截器回调
  411. * @return {Object} - 返回操作后的response
  412. * @callback Request~responseCallback
  413. * @param {Object} response - 请求结果 response
  414. */
  415. /**
  416. * 响应错误拦截器回调
  417. * @return {Object} - 返回操作后的response
  418. * @callback Request~responseErrCallback
  419. * @param {Object} response - 请求结果 response
  420. */