request.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. /**
  2. * Request 0.0.7
  3. * @Class uni-app request网络请求库
  4. * @Author lu-ch
  5. * @Date 2019-07-11
  6. * @Email webwork.s@qq.com
  7. * http://ext.dcloud.net.cn/plugin?id=392
  8. * **/
  9. import qs from 'qs'
  10. import constant from '@/constant/index'
  11. // import common from '@/utils/common'
  12. import { parse } from '@/utils/util'
  13. const Base64 = require('js-base64').Base64
  14. class Request {
  15. config = {
  16. // #ifdef H5
  17. baseUrl: process.env.NODE_ENV == 'development' ? '/api' : constant.hostUrl,
  18. // #endif
  19. // #ifdef MP-WEIXIN
  20. baseUrl: constant.hostUrl,
  21. // #endif
  22. header: {
  23. 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  24. },
  25. data: {},
  26. method: 'GET',
  27. dataType: 'json', /* 如设为json,会对返回的数据做一次 JSON.parse */
  28. responseType: 'text',
  29. success() { },
  30. fail() { },
  31. complete() { }
  32. }
  33. static posUrl(url) { /* 判断url是否为绝对路径 */
  34. return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
  35. }
  36. interceptor = {
  37. request: (f) => {
  38. if (f && typeof f === 'function') {
  39. this.requestBeforeFun = f
  40. }
  41. },
  42. response: (f) => {
  43. if (f && typeof f === 'function') {
  44. this.requestComFun = f
  45. }
  46. }
  47. }
  48. requestBeforeFun(config, cancel) {
  49. let token = ''
  50. try {
  51. const st = uni.getStorageSync('token')
  52. if (st) {
  53. token = st
  54. }
  55. } catch (e) {
  56. console.error(e, '获取token异常')
  57. }
  58. config.header = {
  59. ...config.header
  60. }
  61. // 将token 放入header
  62. if (token) {
  63. config.header['token'] = token
  64. }
  65. // const token = uni.getStorageSync('token')
  66. // config.data = JSON.stringify(config.data);
  67. config.headers = {
  68. 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  69. }
  70. // if (token) { // 判断是否存在token,如果存在的话,则每个http header都加上token
  71. // // axios.defaults.headers.common['token'] = token;
  72. // config.headers.token = token
  73. // }
  74. // config.headers.HkdsRequestFrom = window.location.href
  75. // config.header.userRegion = Base64.encode(uni.getStorageSync('userRegion')) || null
  76. // config.header['x-client-hash'] = uni.getStorageSync('client_hash') || null
  77. const userRegion = Base64.encode(uni.getStorageSync('userRegion')) || null
  78. // if (userRegion) {
  79. // config.header.userRegion = userRegion
  80. // }
  81. const account = uni.getStorageSync('account') || null
  82. if (account) {
  83. config.header['account'] = account
  84. }
  85. const source = uni.getStorageSync('source') || null
  86. if (source) {
  87. config.header['source'] = source
  88. }
  89. if (config.config.loading) {
  90. uni.showLoading({
  91. title: '',
  92. mask: true
  93. })
  94. }
  95. return config
  96. }
  97. requestComFun(response) {
  98. if (response.config.config.loading) {
  99. uni.hideLoading()
  100. }
  101. // const client_hash = response.header.client_hash || null
  102. // console.log('X-Client-Hash', response.header['X-Client-Hash'])
  103. // if (client_hash) {
  104. // uni.setStorageSync('client_hash', client_hash)
  105. // }
  106. return response
  107. }
  108. setConfig(f) {
  109. this.config = f(this.config)
  110. }
  111. request(options = {}, config) {
  112. options.baseUrl = options.baseUrl || this.config.baseUrl
  113. options.dataType = options.dataType || this.config.dataType
  114. options.url = Request.posUrl(options.url) ? options.url : (options.baseUrl + options.url)
  115. options.data = qs.stringify(options.data) || {}
  116. options.header = options.header || this.config.header
  117. options.method = options.method || this.config.method
  118. return new Promise((resolve, reject) => {
  119. let next = true
  120. let _config = null
  121. options.complete = (response) => {
  122. const statusCode = response.statusCode
  123. response.config = _config
  124. // if(config.method === 'get') {
  125. // response.config.config = config
  126. // }else if(config.method === 'post'){
  127. // response.config.config.config = config
  128. // }
  129. response.config.config = config
  130. response = this.requestComFun(response)
  131. // 全局忽略错误,在单个请求里面自行处理
  132. if (config.hideError) {
  133. resolve(response.data)
  134. }
  135. if (statusCode === 200) { // 成功
  136. if (response.data.code === 1) {
  137. resolve(response.data)
  138. } else {
  139. // 无权限或者登录过期
  140. if (response.data.code && response.data.code == -100) {
  141. uni.removeStorageSync('token')
  142. uni.showToast({
  143. title: '登陆过期,正在返回登录页...',
  144. icon: 'none',
  145. mask: true
  146. })
  147. setTimeout(() => {
  148. uni.reLaunch({
  149. url: `/pages/page/login/index`
  150. })
  151. }, 2000)
  152. } else {
  153. if (!config.hideError) {
  154. uni.showToast({
  155. title: response.data.msg,
  156. icon: 'none',
  157. mask: true
  158. })
  159. }
  160. reject(response.data)
  161. }
  162. }
  163. } else {
  164. reject(response)
  165. }
  166. }
  167. const cancel = (t = 'handle cancel') => {
  168. const err = {
  169. errMsg: t,
  170. config: afC
  171. }
  172. reject(err)
  173. next = false
  174. }
  175. const afC = { ...this.config, ...options, config: config }
  176. _config = { ...afC, ...this.requestBeforeFun(afC, cancel) }
  177. if (!next) return
  178. uni.request(_config)
  179. })
  180. }
  181. get(url, data = {}, options = {}, config = {}) {
  182. // options.url = url + common.queryData(data, true)
  183. options.url = url + parse(data, true)
  184. options.data = {}
  185. options.method = 'GET'
  186. return this.request(options, config)
  187. }
  188. post(url, data = {}, options = {}, config = {}) {
  189. options.url = url
  190. options.data = data
  191. options.method = 'POST'
  192. return this.request(options, config)
  193. }
  194. }
  195. export default new Request()