request.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. // #ifdef APP-PLUS
  23. baseUrl: constant.hostUrl,
  24. // #endif
  25. header: {
  26. 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  27. },
  28. data: {},
  29. method: 'GET',
  30. dataType: 'json', /* 如设为json,会对返回的数据做一次 JSON.parse */
  31. responseType: 'text',
  32. success() { },
  33. fail() { },
  34. complete() { }
  35. }
  36. static posUrl(url) { /* 判断url是否为绝对路径 */
  37. return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
  38. }
  39. interceptor = {
  40. request: (f) => {
  41. if (f && typeof f === 'function') {
  42. this.requestBeforeFun = f
  43. }
  44. },
  45. response: (f) => {
  46. if (f && typeof f === 'function') {
  47. this.requestComFun = f
  48. }
  49. }
  50. }
  51. requestBeforeFun(config, cancel) {
  52. let token = ''
  53. try {
  54. const st = uni.getStorageSync('token')
  55. if (st) {
  56. token = st
  57. }
  58. } catch (e) {
  59. console.error(e, '获取token异常')
  60. }
  61. config.header = {
  62. ...config.header
  63. }
  64. // 将token 放入header
  65. if (token) {
  66. config.header['token'] = token
  67. }
  68. // const token = uni.getStorageSync('token')
  69. // config.data = JSON.stringify(config.data);
  70. config.headers = {
  71. 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  72. }
  73. // if (token) { // 判断是否存在token,如果存在的话,则每个http header都加上token
  74. // // axios.defaults.headers.common['token'] = token;
  75. // config.headers.token = token
  76. // }
  77. // config.headers.HkdsRequestFrom = window.location.href
  78. // config.header.userRegion = Base64.encode(uni.getStorageSync('userRegion')) || null
  79. // config.header['x-client-hash'] = uni.getStorageSync('client_hash') || null
  80. const userRegion = Base64.encode(uni.getStorageSync('userRegion')) || null
  81. // if (userRegion) {
  82. // config.header.userRegion = userRegion
  83. // }
  84. const account = uni.getStorageSync('account') || null
  85. if (account) {
  86. config.header['account'] = account
  87. }
  88. // const source = uni.getStorageSync('source') || null
  89. // if (source) {
  90. // config.header['source'] = source
  91. // }
  92. if (constant.source == 'mobile') {
  93. const shopId = uni.getStorageSync('shopId') || 0
  94. if (shopId) {
  95. config.header['shopId'] = shopId
  96. }
  97. }
  98. if (config.config.loading) {
  99. uni.showLoading({
  100. title: '',
  101. mask: true
  102. })
  103. }
  104. return config
  105. }
  106. requestComFun(response) {
  107. if (response.config.config.loading) {
  108. uni.hideLoading()
  109. }
  110. // const client_hash = response.header.client_hash || null
  111. // console.log('X-Client-Hash', response.header['X-Client-Hash'])
  112. // if (client_hash) {
  113. // uni.setStorageSync('client_hash', client_hash)
  114. // }
  115. return response
  116. }
  117. setConfig(f) {
  118. this.config = f(this.config)
  119. }
  120. request(options = {}, config) {
  121. options.baseUrl = options.baseUrl || this.config.baseUrl
  122. options.dataType = options.dataType || this.config.dataType
  123. options.url = Request.posUrl(options.url) ? options.url : (options.baseUrl + options.url)
  124. options.data = qs.stringify(options.data) || {}
  125. options.header = options.header || this.config.header
  126. options.method = options.method || this.config.method
  127. return new Promise((resolve, reject) => {
  128. let next = true
  129. let _config = null
  130. options.complete = (response) => {
  131. const statusCode = response.statusCode
  132. response.config = _config
  133. // if(config.method === 'get') {
  134. // response.config.config = config
  135. // }else if(config.method === 'post'){
  136. // response.config.config.config = config
  137. // }
  138. response.config.config = config
  139. response = this.requestComFun(response)
  140. // 全局忽略错误,在单个请求里面自行处理
  141. if (config.hideError) {
  142. resolve(response.data)
  143. }
  144. if (statusCode === 200) { // 成功
  145. if (response.data.code === 1) {
  146. resolve(response.data)
  147. } else {
  148. // 返回错误信息
  149. if (response.data.code == 0) {
  150. if (!config.hideError) {
  151. uni.showToast({ title: response.data.msg, icon: 'none', mask: true })
  152. }
  153. reject(response.data)
  154. } else if (response.data.code && response.data.code == -1) {
  155. // 无权限或者登录过期
  156. // uni.removeStorageSync('token')
  157. // uni.showToast({ title: '登录已失效...', icon: 'none', mask: true })
  158. // setTimeout(() => {
  159. // getCheckLogin()
  160. // }, 1000)
  161. } else if (response.data.code == 2) {
  162. uni.removeStorageSync('token')
  163. uni.removeStorageSync('shopUser')
  164. uni.removeStorageSync('account')
  165. uni.showToast({ title: '登录已失效..', icon: 'none', mask: true })
  166. setTimeout(() => {
  167. //getCheckLogin()
  168. }, 1000)
  169. } else {
  170. console.log('response.data', response.data)
  171. if (!config.hideError) {
  172. // this.$msg(response.data.msg)
  173. uni.showToast({
  174. title: response.data.msg,
  175. icon: 'none',
  176. mask: true
  177. })
  178. }
  179. reject(response.data)
  180. }
  181. }
  182. } else {
  183. reject(response)
  184. }
  185. }
  186. const cancel = (t = 'handle cancel') => {
  187. const err = {
  188. errMsg: t,
  189. config: afC
  190. }
  191. reject(err)
  192. next = false
  193. }
  194. const afC = { ...this.config, ...options, config: config }
  195. _config = { ...afC, ...this.requestBeforeFun(afC, cancel) }
  196. if (!next) return
  197. uni.request(_config)
  198. })
  199. }
  200. get(url, data = {}, options = {}, config = {}) {
  201. // options.url = url + common.queryData(data, true)
  202. options.url = url + parse(data)
  203. options.data = {}
  204. options.method = 'GET'
  205. return this.request(options, config)
  206. }
  207. post(url, data = {}, options = {}, config = {}) {
  208. options.url = url
  209. options.data = data
  210. options.method = 'POST'
  211. return this.request(options, config)
  212. }
  213. }
  214. export default new Request()