request.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. /**
  2. * 网络请求封装
  3. */
  4. // 固定的 clientid
  5. const CLIENT_ID = '2f847927afb2b3ebeefc870c13d623f2'
  6. // 基础 URL(根据实际情况修改)
  7. const BASE_URL = 'http://127.0.0.1:8080'
  8. /**
  9. * 封装的请求方法
  10. * @param {Object} options - 请求配置
  11. * @param {String} options.url - 请求地址
  12. * @param {String} options.method - 请求方法,默认 GET
  13. * @param {Object} options.data - 请求参数
  14. * @param {Object} options.header - 额外的请求头
  15. * @returns {Promise}
  16. */
  17. const request = (options) => {
  18. return new Promise((resolve, reject) => {
  19. // 获取存储的 token
  20. const token = uni.getStorageSync('token') || ''
  21. uni.request({
  22. url: BASE_URL + options.url,
  23. method: options.method || 'GET',
  24. data: options.data || {},
  25. header: {
  26. 'Content-Type': 'application/json',
  27. 'clientid': CLIENT_ID,
  28. 'token': token,
  29. ...options.header
  30. },
  31. success: (res) => {
  32. const { code, msg, data, total, rows } = res.data
  33. // 根据状态码处理
  34. switch (code) {
  35. case 200:
  36. // 操作成功,返回数据
  37. if (total !== undefined && rows !== undefined) {
  38. // 分页查询返回体
  39. resolve({
  40. total,
  41. rows,
  42. code,
  43. msg
  44. })
  45. } else {
  46. // 一般返回体
  47. resolve({
  48. code,
  49. msg,
  50. data
  51. })
  52. }
  53. break
  54. case 401:
  55. // token 失效
  56. uni.showToast({
  57. title: 'token失效,请重新登录',
  58. icon: 'none',
  59. duration: 2000
  60. })
  61. // 清除 token
  62. uni.removeStorageSync('token')
  63. // 跳转到登录页(如果有的话)
  64. // uni.navigateTo({ url: '/pages/login/login' })
  65. reject({ code, msg: 'token失效' })
  66. break
  67. case 500:
  68. // 系统错误
  69. uni.showToast({
  70. title: '系统错误',
  71. icon: 'none',
  72. duration: 2000
  73. })
  74. reject({ code, msg: '系统错误' })
  75. break
  76. case 501:
  77. // 提示返回的 msg
  78. uni.showToast({
  79. title: msg || '请求失败',
  80. icon: 'none',
  81. duration: 2000
  82. })
  83. reject({ code, msg })
  84. break
  85. default:
  86. // 其他状态码
  87. uni.showToast({
  88. title: msg || '请求失败',
  89. icon: 'none',
  90. duration: 2000
  91. })
  92. reject({ code, msg })
  93. break
  94. }
  95. },
  96. fail: (err) => {
  97. uni.showToast({
  98. title: '网络请求失败',
  99. icon: 'none',
  100. duration: 2000
  101. })
  102. reject(err)
  103. }
  104. })
  105. })
  106. }
  107. export default request