request.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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 == 0) {
  147. if (!config.hideError) {
  148. // this.$msg(response.data.msg)
  149. uni.showToast({
  150. title: response.data.msg,
  151. icon: 'none',
  152. mask: true
  153. })
  154. }
  155. reject(response.data)
  156. } else if (response.data.code && response.data.code == -1) {
  157. // 无权限或者登录过期
  158. uni.removeStorageSync('token')
  159. uni.showToast({
  160. title: '登录过期,正在重新登录...',
  161. icon: 'none',
  162. mask: true
  163. })
  164. setTimeout(() => {
  165. getCheckLogin()
  166. // uni.reLaunch({
  167. // url: `/pages/page/login/index`
  168. // })
  169. }, 1000)
  170. } else if (response.data.code == 2) {
  171. uni.removeStorageSync('token')
  172. uni.removeStorageSync('shopUser')
  173. uni.removeStorageSync('account')
  174. uni.showToast({
  175. title: '登录失效,正在重新登录...',
  176. icon: 'none',
  177. mask: true
  178. })
  179. setTimeout(() => {
  180. getCheckLogin()
  181. // uni.reLaunch({
  182. // url: `/pages/page/login/index`
  183. // })
  184. }, 1000)
  185. } else {
  186. console.log('response.data', response.data)
  187. if (!config.hideError) {
  188. // this.$msg(response.data.msg)
  189. uni.showToast({
  190. title: response.data.msg,
  191. icon: 'none',
  192. mask: true
  193. })
  194. }
  195. reject(response.data)
  196. }
  197. }
  198. } else {
  199. reject(response)
  200. }
  201. }
  202. const cancel = (t = 'handle cancel') => {
  203. const err = {
  204. errMsg: t,
  205. config: afC
  206. }
  207. reject(err)
  208. next = false
  209. }
  210. const afC = { ...this.config, ...options, config: config }
  211. _config = { ...afC, ...this.requestBeforeFun(afC, cancel) }
  212. if (!next) return
  213. uni.request(_config)
  214. })
  215. }
  216. get(url, data = {}, options = {}, config = {}) {
  217. // options.url = url + common.queryData(data, true)
  218. options.url = url + parse(data)
  219. options.data = {}
  220. options.method = 'GET'
  221. return this.request(options, config)
  222. }
  223. post(url, data = {}, options = {}, config = {}) {
  224. options.url = url
  225. options.data = data
  226. options.method = 'POST'
  227. return this.request(options, config)
  228. }
  229. }
  230. export default new Request()