request.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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 { TOKEN_STORAGE_KEY } from '@/constant/storageKeys'
  12. // import common from '@/utils/common'
  13. import { parse } from '@/utils/util'
  14. import store from '@/store'
  15. const Base64 = require('js-base64').Base64
  16. class Request {
  17. config = {
  18. // #ifdef H5
  19. // baseUrl: process.env.NODE_ENV == 'development' ? '/api' : constant.hostUrl,
  20. baseUrl: constant.hostUrl,
  21. // #endif
  22. // #ifdef MP-WEIXIN
  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 isAbsoluteUrl(url) { /* 判断url是否为绝对路径 */
  37. return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
  38. }
  39. static posUrl(url) { /* 兼容旧方法名 */
  40. return Request.isAbsoluteUrl(url)
  41. }
  42. interceptor = {
  43. request: (f) => {
  44. if (f && typeof f === 'function') {
  45. this.requestBeforeFun = f
  46. }
  47. },
  48. response: (f) => {
  49. if (f && typeof f === 'function') {
  50. this.requestComFun = f
  51. }
  52. }
  53. }
  54. requestBeforeFun(config, cancel) {
  55. let token = ''
  56. try {
  57. const st = uni.getStorageSync(TOKEN_STORAGE_KEY)
  58. if (st) {
  59. token = st
  60. }
  61. } catch (e) {
  62. console.error(e, '获取token异常')
  63. }
  64. config.header = {
  65. ...config.header
  66. }
  67. // 将token 放入header
  68. if (token) {
  69. config.header['token'] = token
  70. }
  71. // const token = uni.getStorageSync('token')
  72. // config.data = JSON.stringify(config.data);
  73. // 统一使用 config.header,避免混用 headers
  74. // if (token) { // 判断是否存在token,如果存在的话,则每个http header都加上token
  75. // // axios.defaults.headers.common['token'] = token;
  76. // config.headers.token = token
  77. // }
  78. // config.headers.HkdsRequestFrom = window.location.href
  79. // config.header.userRegion = Base64.encode(uni.getStorageSync('userRegion')) || null
  80. // config.header['x-client-hash'] = uni.getStorageSync('client_hash') || null
  81. // const userRegion = Base64.encode(uni.getStorageSync('userRegion')) || null
  82. // if (userRegion) {
  83. // config.header.userRegion = userRegion
  84. // }
  85. const account = uni.getStorageSync('account') || null
  86. if (account) {
  87. config.header['account'] = account
  88. }
  89. // const source = uni.getStorageSync('source') || null
  90. // if (source) {
  91. // config.header['source'] = source
  92. // }
  93. if (constant.source == 'mobile') {
  94. const shopId = uni.getStorageSync('shopId') || 0
  95. if (shopId) {
  96. config.header['shopId'] = shopId
  97. }
  98. }
  99. if (config.config.loading) {
  100. uni.showLoading({
  101. title: '',
  102. mask: true
  103. })
  104. }
  105. return config
  106. }
  107. requestComFun(response) {
  108. if (response.config.config.loading) {
  109. uni.hideLoading()
  110. }
  111. // const client_hash = response.header.client_hash || null
  112. // console.log('X-Client-Hash', response.header['X-Client-Hash'])
  113. // if (client_hash) {
  114. // uni.setStorageSync('client_hash', client_hash)
  115. // }
  116. return response
  117. }
  118. /**
  119. * 处理鉴权失效后的通用逻辑
  120. * @param {string} currentRoute 当前页面路由
  121. */
  122. handleAuthExpired(currentRoute) {
  123. uni.removeStorageSync(TOKEN_STORAGE_KEY)
  124. store.commit('setLoginInfo', {})
  125. uni.showToast({
  126. title: '加载中...',
  127. icon: 'none',
  128. mask: true
  129. })
  130. const account = uni.getStorageSync('account')
  131. if (account) {
  132. setTimeout(() => {
  133. uni.reLaunch({
  134. url: '/' + currentRoute + '?account=' + account
  135. })
  136. }, 1000)
  137. } else {
  138. setTimeout(() => {
  139. uni.reLaunch({
  140. url: `/pages/home/recent`
  141. })
  142. }, 1000)
  143. }
  144. }
  145. setConfig(f) {
  146. this.config = f(this.config)
  147. }
  148. /**
  149. * 发送 HTTP 请求
  150. * @param {Object} options uni.request 的参数子集
  151. * @param {Object} config 业务控制参数 { loading?: boolean, hideError?: boolean }
  152. */
  153. request(options = {}, config) {
  154. options.baseUrl = options.baseUrl || this.config.baseUrl
  155. options.dataType = options.dataType || this.config.dataType
  156. options.url = Request.posUrl(options.url) ? options.url : (options.baseUrl + options.url)
  157. options.data = qs.stringify(options.data) || {}
  158. options.header = options.header || this.config.header
  159. options.method = options.method || this.config.method
  160. return new Promise((resolve, reject) => {
  161. let next = true
  162. let _config = null
  163. options.complete = (response) => {
  164. const statusCode = response.statusCode
  165. response.config = _config
  166. // if(config.method === 'get') {
  167. // response.config.config = config
  168. // }else if(config.method === 'post'){
  169. // response.config.config.config = config
  170. // }
  171. response.config.config = config
  172. response = this.requestComFun(response)
  173. // 全局忽略错误,在单个请求里面自行处理
  174. if (config.hideError) {
  175. resolve(response.data)
  176. return
  177. }
  178. if (statusCode === 200) { // 成功
  179. if (response.data.code === 1) {
  180. resolve(response.data)
  181. } else {
  182. let currentPages = getCurrentPages()[0].route
  183. // 返回错误信息
  184. if (response.data.code == 0) {
  185. if (!config.hideError) {
  186. // this.$msg(response.data.msg)
  187. uni.showToast({
  188. title: response.data.msg,
  189. icon: 'none',
  190. mask: true
  191. })
  192. }
  193. reject(response.data)
  194. } else if (response.data.code && response.data.code == -1) {
  195. // this.handleAuthExpired(currentPages)
  196. // -1 仅作为业务失败返回,不触发自动登出
  197. resolve(response.data)
  198. } else if (response.data.code == 2) {
  199. this.handleAuthExpired(currentPages)
  200. } else {
  201. console.log('response.data', response.data)
  202. if (!config.hideError) {
  203. // this.$msg(response.data.msg)
  204. uni.showToast({
  205. title: response.data.msg,
  206. icon: 'none',
  207. mask: true
  208. })
  209. }
  210. reject(response.data)
  211. }
  212. }
  213. } else {
  214. reject(response)
  215. }
  216. }
  217. const cancel = (t = 'handle cancel') => {
  218. const err = {
  219. errMsg: t,
  220. config: afC
  221. }
  222. reject(err)
  223. next = false
  224. }
  225. const afC = { ...this.config, ...options, config: config }
  226. _config = { ...afC, ...this.requestBeforeFun(afC, cancel) }
  227. if (!next) return
  228. uni.request(_config)
  229. })
  230. }
  231. get(url, data = {}, options = {}, config = {}) {
  232. const account = uni.getStorageSync('account') || 0;
  233. const hdId = uni.getStorageSync('hdId') || 0;
  234. if(account != 0 && hdId != 0){
  235. options.url = url + parse({...data,'account':account,'hdId':hdId})
  236. } else {
  237. // console.log("-----get----- data: ", data);
  238. // 判断data中有无account和hdId
  239. if(data.account && data.hdId){
  240. options.url = url + parse({...data})
  241. } else if(data.account && !data.hdId){
  242. options.url = url + parse({...data, 'hdId':hdId})
  243. } else if(!data.account && data.hdId){
  244. options.url = url + parse({...data, 'account':account})
  245. } else {
  246. options.url = url + parse({...data, 'account':account, 'hdId':hdId})
  247. }
  248. }
  249. options.data = {}
  250. options.method = 'GET'
  251. return this.request(options, config)
  252. }
  253. post(url, data = {}, options = {}, config = {}) {
  254. const account = uni.getStorageSync('account') || 0;
  255. const hdId = uni.getStorageSync('hdId') || 0;
  256. if(account != 0 && hdId != 0){
  257. options.url = url+'?account='+account+'&hdId='+hdId
  258. } else {
  259. //console.log("-----post----- data: ", data);
  260. // 判断data中有无account和hdId
  261. if(data.account && data.hdId){
  262. options.url = url + parse({...data, 'account':data.account, 'hdId':data.hdId})
  263. } else if(data.account && !data.hdId){
  264. options.url = url + parse({...data, 'hdId':hdId})
  265. } else if(!data.account && data.hdId){
  266. options.url = url + parse({...data, 'account':account})
  267. } else {
  268. options.url = url + parse({...data, 'account':account, 'hdId':hdId})
  269. }
  270. }
  271. options.data = data
  272. options.method = 'POST'
  273. return this.request(options, config)
  274. }
  275. }
  276. export default new Request()