人民医院前端

request.js 11KB

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