木邻有你前端代码仓库
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.

110 lines
2.6 KiB

10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 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. } ) {
  10. if (showLoading) uni.showLoading({title: '加载中'})
  11. if(!noToken) {
  12. const token = uni.getStorageSync('token')
  13. if (token) {
  14. header['X-Access-Token'] = token
  15. }else {
  16. uni.showToast({
  17. title: '请先登录',
  18. icon: 'none'
  19. })
  20. uni.reLaunch({ url: '/subPages/login/login' })
  21. return
  22. }
  23. }
  24. return new Promise((resolve, reject) => {
  25. uni.request({
  26. url: config.baseURL + url,
  27. method,
  28. data,
  29. header: {
  30. 'Content-Type': 'application/x-www-form-urlencoded',
  31. ...header
  32. },
  33. success: (res) => {
  34. console.log(`Success ${method} ${url}`, res);
  35. // 优先处理业务逻辑响应
  36. if (res.statusCode === 200 && res.data) {
  37. // 业务成功
  38. if (res.data.code === 200 && res.data.result !== null) {
  39. resolve(res.data)
  40. return
  41. }
  42. // 业务失败但有具体错误信息
  43. const errorMsg = res.data.message || '请求失败'
  44. uni.showToast({
  45. title: errorMsg,
  46. icon: 'none'
  47. })
  48. reject({
  49. code: res.data.code,
  50. message: errorMsg,
  51. data: res.data
  52. })
  53. return
  54. }
  55. // 处理HTTP状态码错误(无有效响应体的情况)
  56. const error = {
  57. code: res.statusCode,
  58. message: '网络请求错误'
  59. }
  60. switch (res.statusCode) {
  61. case 401:
  62. case 403:
  63. uni.removeStorageSync('token')
  64. uni.reLaunch({ url: '/subPages/login/login' })
  65. error.message = '登录已过期,请重新登录'
  66. break;
  67. case 404:
  68. error.message = '资源不存在'
  69. break;
  70. case 500:
  71. error.message = '服务器错误'
  72. break;
  73. }
  74. uni.showToast({
  75. title: error.message,
  76. icon: 'none'
  77. })
  78. reject(error)
  79. },
  80. fail: (err) => {
  81. console.log(`Fail ${method} ${url}`, err);
  82. const errorMsg = err.errMsg || '请求失败'
  83. uni.showToast({
  84. title: errorMsg,
  85. icon: 'none'
  86. })
  87. reject({
  88. code: -1,
  89. message: errorMsg,
  90. data: err
  91. })
  92. },
  93. complete: () => {
  94. if (showLoading) {
  95. uni.hideLoading()
  96. }
  97. }
  98. })
  99. })
  100. }