request.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. 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 isAbsoluteUrl(url) { /* 判断url是否为绝对路径 */
  36. return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
  37. }
  38. static posUrl(url) { /* 兼容旧方法名 */
  39. return Request.isAbsoluteUrl(url)
  40. }
  41. interceptor = {
  42. request: (f) => {
  43. if (f && typeof f === 'function') {
  44. this.requestBeforeFun = f
  45. }
  46. },
  47. response: (f) => {
  48. if (f && typeof f === 'function') {
  49. this.requestComFun = f
  50. }
  51. }
  52. }
  53. requestBeforeFun(config, cancel) {
  54. let token = ''
  55. try {
  56. const st = uni.getStorageSync('token')
  57. if (st) {
  58. token = st
  59. }
  60. } catch (e) {
  61. console.error(e, '获取token异常')
  62. }
  63. config.header = {
  64. ...config.header
  65. }
  66. // 将token 放入header
  67. if (token) {
  68. config.header['token'] = token
  69. }
  70. // const token = uni.getStorageSync('token')
  71. // config.data = JSON.stringify(config.data);
  72. // 统一使用 config.header,避免混用 headers
  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. /**
  118. * 处理鉴权失效后的通用逻辑
  119. * @param {string} currentRoute 当前页面路由
  120. */
  121. handleAuthExpired(currentRoute) {
  122. uni.removeStorageSync('token')
  123. store.commit('setLoginInfo', {})
  124. uni.showToast({
  125. title: '加载中...',
  126. icon: 'none',
  127. mask: true
  128. })
  129. const account = uni.getStorageSync('account')
  130. if (account) {
  131. setTimeout(() => {
  132. uni.reLaunch({
  133. url: '/' + currentRoute + '?account=' + account
  134. })
  135. }, 1000)
  136. } else {
  137. setTimeout(() => {
  138. uni.reLaunch({
  139. url: `/pages/home/recent`
  140. })
  141. }, 1000)
  142. }
  143. }
  144. setConfig(f) {
  145. this.config = f(this.config)
  146. }
  147. /**
  148. * 发送 HTTP 请求
  149. * @param {Object} options uni.request 的参数子集
  150. * @param {Object} config 业务控制参数 { loading?: boolean, hideError?: boolean }
  151. */
  152. request(options = {}, config) {
  153. options.baseUrl = options.baseUrl || this.config.baseUrl
  154. options.dataType = options.dataType || this.config.dataType
  155. options.url = Request.posUrl(options.url) ? options.url : (options.baseUrl + options.url)
  156. options.data = qs.stringify(options.data) || {}
  157. options.header = options.header || this.config.header
  158. options.method = options.method || this.config.method
  159. return new Promise((resolve, reject) => {
  160. let next = true
  161. let _config = null
  162. options.complete = (response) => {
  163. const statusCode = response.statusCode
  164. response.config = _config
  165. // if(config.method === 'get') {
  166. // response.config.config = config
  167. // }else if(config.method === 'post'){
  168. // response.config.config.config = config
  169. // }
  170. response.config.config = config
  171. response = this.requestComFun(response)
  172. // 全局忽略错误,在单个请求里面自行处理
  173. if (config.hideError) {
  174. resolve(response.data)
  175. return
  176. }
  177. if (statusCode === 200) { // 成功
  178. if (response.data.code === 1) {
  179. resolve(response.data)
  180. } else {
  181. let currentPages = getCurrentPages()[0].route
  182. // 返回错误信息
  183. if (response.data.code == 0) {
  184. if (!config.hideError) {
  185. // this.$msg(response.data.msg)
  186. uni.showToast({
  187. title: response.data.msg,
  188. icon: 'none',
  189. mask: true
  190. })
  191. }
  192. reject(response.data)
  193. } else if (response.data.code && response.data.code == -1) {
  194. this.handleAuthExpired(currentPages)
  195. } else if (response.data.code == 2) {
  196. this.handleAuthExpired(currentPages)
  197. } else {
  198. console.log('response.data', response.data)
  199. if (!config.hideError) {
  200. // this.$msg(response.data.msg)
  201. uni.showToast({
  202. title: response.data.msg,
  203. icon: 'none',
  204. mask: true
  205. })
  206. }
  207. reject(response.data)
  208. }
  209. }
  210. } else {
  211. reject(response)
  212. }
  213. }
  214. const cancel = (t = 'handle cancel') => {
  215. const err = {
  216. errMsg: t,
  217. config: afC
  218. }
  219. reject(err)
  220. next = false
  221. }
  222. const afC = { ...this.config, ...options, config: config }
  223. _config = { ...afC, ...this.requestBeforeFun(afC, cancel) }
  224. if (!next) return
  225. uni.request(_config)
  226. })
  227. }
  228. get(url, data = {}, options = {}, config = {}) {
  229. const account = uni.getStorageSync('account') || 0;
  230. const hdId = uni.getStorageSync('hdId') || 0;
  231. if(account != 0 && hdId != 0){
  232. options.url = url + parse({...data,'account':account,'hdId':hdId})
  233. } else {
  234. // 判断data中有无account和hdId
  235. if(data.account && data.hdId){
  236. options.url = url + parse({...data})
  237. } else if(data.account && !data.hdId){
  238. options.url = url + parse({...data, 'hdId':hdId})
  239. } else if(!data.account && data.hdId){
  240. options.url = url + parse({...data, 'account':account})
  241. } else {
  242. options.url = url + parse({...data, 'account':account, 'hdId':hdId})
  243. }
  244. }
  245. options.data = {}
  246. options.method = 'GET'
  247. return this.request(options, config)
  248. }
  249. post(url, data = {}, options = {}, config = {}) {
  250. const account = uni.getStorageSync('account') || 0;
  251. const hdId = uni.getStorageSync('hdId') || 0;
  252. if(account != 0 && hdId != 0){
  253. options.url = url+'?account='+account+'&hdId='+hdId
  254. } else {
  255. // 判断data中有无account和hdId
  256. if(data.account && data.hdId){
  257. options.url = url + parse({...data})
  258. } else if(data.account && !data.hdId){
  259. options.url = url + parse({...data, 'hdId':hdId})
  260. } else if(!data.account && data.hdId){
  261. options.url = url + parse({...data, 'account':account})
  262. } else {
  263. options.url = url + parse({...data, 'account':account, 'hdId':hdId})
  264. }
  265. }
  266. options.data = data
  267. options.method = 'POST'
  268. return this.request(options, config)
  269. }
  270. }
  271. export default new Request()