request.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. /**
  2. * 网络请求
  3. * @author yxk
  4. */
  5. import App from '../main.js'
  6. import { BASE_URL_FN } from '../config.js'
  7. let loadingCount = 0
  8. const closeLoading = () => {
  9. if (loadingCount <= 0) {
  10. loadingCount = 0
  11. uni.hideLoading();
  12. }
  13. }
  14. const service = (config) => {
  15. if (!config.hideLoading && loadingCount === 0) {
  16. uni.showLoading({
  17. mask: true,
  18. title: '加载中'
  19. })
  20. }
  21. loadingCount++
  22. if (!config.header) {
  23. config.header = {}
  24. }
  25. if (config.requestType === 'form') {
  26. config.header = {
  27. ...config.header,
  28. 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  29. }
  30. }
  31. const token = uni.getStorageSync('token') || null
  32. const flag = config.hasOwnProperty('requiredAuth') ? !!config.requiredAuth : true
  33. if (token) {
  34. config.header = {
  35. ...config.header,
  36. 'Admin-Token': token
  37. }
  38. } else if (flag) {
  39. // 非登录相关接口,没有 token 直接转到登录页
  40. loadingCount = 0
  41. uni.hideLoading()
  42. App.$Router.reLaunch('/pages_login/index')
  43. return Promise.reject()
  44. }
  45. let url = ''
  46. if (!config.url.startsWith('http')) {
  47. url = BASE_URL_FN() + config.url
  48. } else {
  49. url = config.url
  50. }
  51. const appid = uni.getStorageSync('appid') || null
  52. if (appid) {
  53. config.header.k = appid
  54. }
  55. // #ifdef H5
  56. config.withCredentials = true
  57. // #endif
  58. return new Promise((resolve, reject) => {
  59. uni.request({
  60. ...config,
  61. url,
  62. success: res => {
  63. loadingCount--
  64. closeLoading()
  65. const data = res.data
  66. if (config.responseType === 'arraybuffer') {
  67. resolve(res)
  68. return
  69. }
  70. if (data.code === 302) {
  71. App.$Router.reLaunch('/pages/login/index')
  72. let str = ''
  73. if (data.extra && data.extra === 1) {
  74. str = `您的账号${data.extraTime}在别处登录。如非本人操作,则密码可能已泄漏,建议修改密码`
  75. } else {
  76. str = '登录已失效,请重新登录'
  77. }
  78. setTimeout(() => {
  79. App.$toast(str)
  80. str = null
  81. }, 500)
  82. reject('登录已失效,请重新登录')
  83. return
  84. }
  85. if (data.code === 0 || data.code === 200) {
  86. if (data.hasOwnProperty('data')) {
  87. resolve(data.data)
  88. } else {
  89. resolve(data)
  90. }
  91. } else {
  92. App.$toast(data.msg)
  93. reject(data.msg)
  94. }
  95. },
  96. fail: error => {
  97. loadingCount--
  98. closeLoading()
  99. reject(error)
  100. }
  101. })
  102. })
  103. }
  104. export default service