木邻有你前端代码仓库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

121 lines
3.0 KiB

3 months ago
3 months ago
2 months ago
3 months ago
3 months ago
3 months ago
2 months ago
1 month ago
3 months ago
2 months ago
1 month ago
3 months ago
2 months ago
3 months ago
2 months ago
3 months ago
  1. import config from "@/config";
  2. export default function request ( {
  3. url = '',
  4. method = 'GET',
  5. data = {},
  6. showLoading = false,
  7. header = {} ,
  8. noToken = false, // 不需要token的接口
  9. showToast = true // 默认显示失败的提示
  10. } ) {
  11. if (showLoading) uni.showLoading({title: '加载中'})
  12. if(!noToken) {
  13. const token = uni.getStorageSync('token')
  14. if (token) {
  15. header['X-Access-Token'] = token
  16. }else {
  17. uni.showToast({
  18. title: '请先登录',
  19. icon: 'none'
  20. })
  21. uni.reLaunch({ url: '/subPages/login/login' })
  22. return
  23. }
  24. }
  25. return new Promise((resolve, reject) => {
  26. uni.request({
  27. url: config.baseURL + url,
  28. method,
  29. data,
  30. header: {
  31. 'Content-Type': 'application/x-www-form-urlencoded',
  32. ...header
  33. },
  34. success: (res) => {
  35. console.log(`Success ${method} ${url}`, res);
  36. // 优先处理业务逻辑响应
  37. if (res.statusCode === 200 && res.data) {
  38. // 业务成功
  39. if (res.data.code === 200 ) {
  40. resolve(res.data)
  41. return
  42. }
  43. // 业务失败但有具体错误信息
  44. const errorMsg = res.data.message || '请求失败'
  45. if (showToast) {
  46. uni.showToast({
  47. title: errorMsg,
  48. icon: 'none'
  49. })
  50. }
  51. // 对于用户被删除 做特殊判断
  52. if (res.data.code === 500 && res.data.message === '操作失败,用户不存在!') {
  53. uni.removeStorageSync('token')
  54. uni.reLaunch({ url: '/subPages/login/login' })
  55. }else{
  56. reject({
  57. code: res.data.code,
  58. message: errorMsg,
  59. data: res.data
  60. })
  61. }
  62. return
  63. }
  64. // 处理HTTP状态码错误(无有效响应体的情况)
  65. const error = {
  66. code: res.statusCode,
  67. message: '网络请求错误'
  68. }
  69. switch (res.statusCode) {
  70. case 401:
  71. case 403:
  72. uni.removeStorageSync('token')
  73. uni.reLaunch({ url: '/subPages/login/login' })
  74. error.message = '登录已过期,请重新登录'
  75. break;
  76. case 404:
  77. error.message = '资源不存在'
  78. break;
  79. case 500:
  80. error.message = '服务器错误'
  81. break;
  82. }
  83. if (showToast) {
  84. uni.showToast({
  85. title: error.message,
  86. icon: 'none'
  87. })
  88. }
  89. reject(error)
  90. },
  91. fail: (err) => {
  92. console.log(`Fail ${method} ${url}`, err);
  93. const errorMsg = err.errMsg || '请求失败'
  94. if (showToast) {
  95. uni.showToast({
  96. title: errorMsg,
  97. icon: 'none'
  98. })
  99. }
  100. reject({
  101. code: -1,
  102. message: errorMsg,
  103. data: err
  104. })
  105. },
  106. complete: () => {
  107. if (showLoading) {
  108. uni.hideLoading()
  109. }
  110. }
  111. })
  112. })
  113. }