request.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import {
  2. getToken
  3. } from '@/utils/auth'
  4. import {
  5. store
  6. } from '@/store/index.js'
  7. // import baseURL from '@/api/base/path.js'
  8. function behindRequist({
  9. url,
  10. data,
  11. method = "GET"
  12. }) {
  13. let token = 'Bearer ' + getToken();
  14. let header = {
  15. Authorization: token
  16. }
  17. return new Promise((resolve, reject) => {
  18. const urlList = uni.getStorageSync('baseUrl')
  19. uni.request({
  20. url: JSON.parse(urlList).baseUrl + url,
  21. data,
  22. method,
  23. header,
  24. timeout: 600000,
  25. sslVerify: false,
  26. success: (res) => {
  27. if (res.statusCode === 200) {
  28. //请求成功
  29. resolve(res.data);
  30. } else if (res.statusCode === 401) {
  31. uni.showToast({
  32. icon: 'none',
  33. title: "未登录或登录状态已超时",
  34. duration: 1500
  35. });
  36. } else if (res.statusCode === 405) {
  37. uni.showToast({
  38. icon: 'none',
  39. title: "请求方法错误",
  40. duration: 1500
  41. });
  42. } else {
  43. uni.showToast({
  44. icon: 'none',
  45. title: "请求错误:" + res.statusCode,
  46. duration: 1500
  47. });
  48. }
  49. },
  50. fail: (err) => {
  51. uni.showToast({
  52. icon: 'none',
  53. title: err.errMsg,
  54. duration: 1500
  55. });
  56. reject(err);
  57. }
  58. })
  59. })
  60. }
  61. // 拦截请求的函数
  62. function request(options) {
  63. return preRequest().then(() => {
  64. // 前置请求成功,继续执行原请求
  65. return behindRequist(options);
  66. }).catch((error) => {
  67. // 前置请求失败,处理错误
  68. uni.showToast({
  69. icon: 'none',
  70. title: error.message || '前置请求失败',
  71. duration: 1500
  72. });
  73. return Promise.reject(error);
  74. });
  75. }
  76. // 前置请求函数
  77. function preRequest() {
  78. let token = 'Bearer ' + getToken();
  79. let header = {
  80. Authorization: token
  81. };
  82. return new Promise((resolve, reject) => {
  83. const urlList = uni.getStorageSync('baseUrl')
  84. console.log(urlList)
  85. uni.request({
  86. url: JSON.parse(urlList).baseUrl + '/business/notification/getHasNotification', // 前置请求的URL
  87. header,
  88. method: 'GET',
  89. success: (res) => {
  90. console.log(res)
  91. if (res.data.code == 200 && !store.isNotification) {
  92. uni.navigateTo({
  93. url: "/pages/notification/index",
  94. success: (resqust) => {
  95. // 通过eventChannel向被打开页面传送数据
  96. resqust.eventChannel.emit("notification", {
  97. data: res.data.data[0]
  98. })
  99. }
  100. })
  101. } else {
  102. // 前置请求成功,继续执行原请求
  103. resolve(true);
  104. }
  105. },
  106. fail: (err) => {
  107. // 前置请求失败,不执行原请求
  108. reject(err);
  109. }
  110. });
  111. });
  112. }
  113. export default {
  114. request
  115. }