request.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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, getCheckLogin } 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 (constant.source == 'mobile') {
  90. const shopId = uni.getStorageSync('shopId') || 0
  91. if (shopId) {
  92. config.header['shopId'] = shopId
  93. }
  94. }
  95. if (config.config.loading) {
  96. uni.showLoading({
  97. title: '',
  98. mask: true
  99. })
  100. }
  101. return config
  102. }
  103. requestComFun(response) {
  104. if (response.config.config.loading) {
  105. uni.hideLoading()
  106. }
  107. // const client_hash = response.header.client_hash || null
  108. // console.log('X-Client-Hash', response.header['X-Client-Hash'])
  109. // if (client_hash) {
  110. // uni.setStorageSync('client_hash', client_hash)
  111. // }
  112. return response
  113. }
  114. setConfig(f) {
  115. this.config = f(this.config)
  116. }
  117. request(options = {}, config) {
  118. options.baseUrl = options.baseUrl || this.config.baseUrl
  119. options.dataType = options.dataType || this.config.dataType
  120. options.url = Request.posUrl(options.url) ? options.url : (options.baseUrl + options.url)
  121. options.data = qs.stringify(options.data) || {}
  122. options.header = options.header || this.config.header
  123. options.method = options.method || this.config.method
  124. return new Promise((resolve, reject) => {
  125. let next = true
  126. let _config = null
  127. options.complete = (response) => {
  128. const statusCode = response.statusCode
  129. response.config = _config
  130. // if(config.method === 'get') {
  131. // response.config.config = config
  132. // }else if(config.method === 'post'){
  133. // response.config.config.config = config
  134. // }
  135. response.config.config = config
  136. response = this.requestComFun(response)
  137. // 全局忽略错误,在单个请求里面自行处理
  138. if (config.hideError) {
  139. resolve(response.data)
  140. }
  141. if (statusCode === 200) { // 成功
  142. if (response.data.code === 1) {
  143. resolve(response.data)
  144. } else {
  145. // 无权限或者登录过期
  146. if (response.data.code && response.data.code == -1) {
  147. uni.removeStorageSync('token')
  148. uni.showToast({
  149. title: '登陆过期,正在重新登录...',
  150. icon: 'none',
  151. mask: true
  152. })
  153. setTimeout(() => {
  154. getCheckLogin()
  155. // uni.reLaunch({
  156. // url: `/pages/page/login/index`
  157. // })
  158. }, 1000)
  159. } else {
  160. if (!config.hideError) {
  161. // this.$msg(response.data.msg)
  162. uni.showToast({
  163. title: response.data.msg,
  164. icon: 'none',
  165. mask: true
  166. })
  167. }
  168. reject(response.data)
  169. }
  170. }
  171. } else {
  172. reject(response)
  173. }
  174. }
  175. const cancel = (t = 'handle cancel') => {
  176. const err = {
  177. errMsg: t,
  178. config: afC
  179. }
  180. reject(err)
  181. next = false
  182. }
  183. const afC = { ...this.config, ...options, config: config }
  184. _config = { ...afC, ...this.requestBeforeFun(afC, cancel) }
  185. if (!next) return
  186. uni.request(_config)
  187. })
  188. }
  189. get(url, data = {}, options = {}, config = {}) {
  190. // options.url = url + common.queryData(data, true)
  191. options.url = url + parse(data)
  192. options.data = {}
  193. options.method = 'GET'
  194. return this.request(options, config)
  195. }
  196. post(url, data = {}, options = {}, config = {}) {
  197. options.url = url
  198. options.data = data
  199. options.method = 'POST'
  200. return this.request(options, config)
  201. }
  202. }
  203. export default new Request()