request.js 11 KB

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