Request.js 12 KB

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