request.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. /**
  2. * 请求封装
  3. * 根据环境自动切换 API 地址
  4. */
  5. import { getCurrentConfig, CURRENT_ENV } from '@/config/index.js'
  6. // 缓存配置
  7. let configCache = null
  8. // 初始化配置
  9. const initConfig = async () => {
  10. if (!configCache) {
  11. configCache = await getCurrentConfig()
  12. console.log('当前环境:', configCache.env, '| API 地址:', configCache.baseUrl)
  13. }
  14. return configCache
  15. }
  16. // 预加载配置
  17. initConfig()
  18. /**
  19. * 统一请求方法
  20. */
  21. export const request = async (options) => {
  22. // 确保配置已加载
  23. const config = await initConfig()
  24. const { baseUrl, timeout, debug } = config
  25. return new Promise((resolve, reject) => {
  26. // 获取 token
  27. const token = uni.getStorageSync('token') || ''
  28. if (debug) {
  29. console.log('Request:', options.method || 'GET', options.url, options.data)
  30. }
  31. uni.request({
  32. url: baseUrl + options.url,
  33. method: options.method || 'GET',
  34. data: options.data || {},
  35. header: {
  36. 'Content-Type': 'application/json',
  37. 'Authorization': token ? `Bearer ${token}` : ''
  38. },
  39. timeout: timeout,
  40. success: (res) => {
  41. const { statusCode, data } = res
  42. if (debug) {
  43. console.log('Response:', statusCode, data)
  44. }
  45. // HTTP 状态码判断
  46. if (statusCode === 200) {
  47. // 业务状态码判断
  48. if (data.code === 0 || data.code === 200 || data.success) {
  49. resolve(data)
  50. } else {
  51. // 业务错误
  52. uni.showToast({
  53. title: data.message || data.msg || '请求失败',
  54. icon: 'none',
  55. duration: 2000
  56. })
  57. reject(data)
  58. }
  59. } else if (statusCode === 401) {
  60. // 未授权,清除缓存并跳转登录页
  61. uni.removeStorageSync('userInfo')
  62. uni.removeStorageSync('token')
  63. uni.reLaunch({
  64. url: '/pages/login/login'
  65. })
  66. reject({ message: '未授权,请重新登录' })
  67. } else {
  68. // 其他错误
  69. uni.showToast({
  70. title: '网络请求失败',
  71. icon: 'none',
  72. duration: 2000
  73. })
  74. reject(res)
  75. }
  76. },
  77. fail: (err) => {
  78. console.error('Request fail:', err)
  79. uni.showToast({
  80. title: '网络连接失败',
  81. icon: 'none',
  82. duration: 2000
  83. })
  84. reject(err)
  85. }
  86. })
  87. })
  88. }
  89. /**
  90. * 快捷请求方法
  91. */
  92. export const get = (url, data) => {
  93. return request({ url, method: 'GET', data })
  94. }
  95. export const post = (url, data) => {
  96. return request({ url, method: 'POST', data })
  97. }
  98. export const put = (url, data) => {
  99. return request({ url, method: 'PUT', data })
  100. }
  101. export const del = (url, data) => {
  102. return request({ url, method: 'DELETE', data })
  103. }
  104. export default request