request.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. import {
  2. server_host
  3. } from "@/config/system"
  4. import {
  5. getCache
  6. } from "./cache";
  7. const auth_whit_list = [
  8. '/auth/c/userCollect/login'
  9. ]
  10. const getData = ({
  11. method,
  12. url,
  13. data,
  14. config
  15. }) => {
  16. return new Promise((resolve, reject) => {
  17. console.log('---', config);
  18. const host = config?.server_host || server_host
  19. console.log(`请求地址 - ${method} - ${host}${url}`);
  20. uni.request({
  21. url: `${host}${url}`,
  22. data,
  23. header: config?.header || {},
  24. method: method,
  25. dataType: config?.dataType || 'json',
  26. success(resp) {
  27. uni.hideLoading()
  28. const code = resp.data.code
  29. if (code == '200') {
  30. console.log('1', resp.data);
  31. resolve(resp.data)
  32. } else if (code == '404') {
  33. reject('找不到服务', code)
  34. } else if (code == '401') {
  35. reject('授权错误', code)
  36. } else {
  37. reject(resp.data.msg, code)
  38. }
  39. },
  40. fail(err) {
  41. uni.hideLoading()
  42. reject('无法连接服务器,请检查您的网络', '-1')
  43. },
  44. })
  45. })
  46. }
  47. const doRequest = ({
  48. method,
  49. url,
  50. data,
  51. config
  52. }) => {
  53. uni.showLoading({
  54. mask: true
  55. })
  56. if (auth_whit_list.includes(url)) {
  57. console.log('白名单 不检查 token');
  58. return getData({
  59. method,
  60. url,
  61. data,
  62. config
  63. })
  64. }
  65. return getCache('token').then(resp => {
  66. console.log('doRequest - getCache', resp, config);
  67. const token = resp.data
  68. if (config) {
  69. if (config.header) {
  70. config.header.token = token
  71. } else {
  72. config.header = {
  73. token
  74. }
  75. }
  76. } else {
  77. config = {
  78. header: {
  79. token
  80. }
  81. }
  82. }
  83. console.log('122');
  84. return getData({
  85. method,
  86. url,
  87. data,
  88. config
  89. })
  90. }).catch((err, code) => {
  91. console.log('err', err, code);
  92. uni.showToast({
  93. title: err,
  94. icon: 'error',
  95. })
  96. if (code == '401') {
  97. uni.redirectTo({
  98. url: '/pages/login/index'
  99. })
  100. }
  101. })
  102. }
  103. const get = ({
  104. url,
  105. data,
  106. config
  107. }) => {
  108. return doRequest({
  109. method: 'GET',
  110. url,
  111. data,
  112. config
  113. })
  114. }
  115. const post = ({
  116. url,
  117. data,
  118. config
  119. }) => {
  120. return doRequest({
  121. method: 'POST',
  122. url,
  123. data,
  124. config
  125. })
  126. }
  127. const request = {
  128. get,
  129. post
  130. }
  131. export default request