Request.js 11 KB

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