request.js 6.9 KB

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