展品维保小程序前端代码接口
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.

114 lines
2.7 KiB

2 weeks 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. reject({
  52. code: res.data.code,
  53. message: errorMsg,
  54. data: res.data
  55. })
  56. return
  57. }
  58. // 处理HTTP状态码错误(无有效响应体的情况)
  59. const error = {
  60. code: res.statusCode,
  61. message: '网络请求错误'
  62. }
  63. switch (res.statusCode) {
  64. case 401:
  65. case 403:
  66. uni.removeStorageSync('token')
  67. uni.reLaunch({ url: '/subPages/login/login' })
  68. error.message = '登录已过期,请重新登录'
  69. break;
  70. case 404:
  71. error.message = '资源不存在'
  72. break;
  73. case 500:
  74. error.message = '服务器错误'
  75. break;
  76. }
  77. if (showToast) {
  78. uni.showToast({
  79. title: error.message,
  80. icon: 'none'
  81. })
  82. }
  83. reject(error)
  84. },
  85. fail: (err) => {
  86. console.log(`Fail ${method} ${url}`, err);
  87. const errorMsg = err.errMsg || '请求失败'
  88. if (showToast) {
  89. uni.showToast({
  90. title: errorMsg,
  91. icon: 'none'
  92. })
  93. }
  94. reject({
  95. code: -1,
  96. message: errorMsg,
  97. data: err
  98. })
  99. },
  100. complete: () => {
  101. if (showLoading) {
  102. uni.hideLoading()
  103. }
  104. }
  105. })
  106. })
  107. }