request.js 2.5 KB

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