request.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /**
  2. * uni-app 网络请求封装
  3. * @author steelwei
  4. */
  5. import { BASE_URL, CLIENT_ID, PLATFORM_CODE, TENANT_ID } from './config'
  6. import { getToken, clearAuth } from './auth'
  7. /**
  8. * 通用请求方法
  9. * @param {Object} options - 请求配置
  10. * @param {string} options.url - 请求路径(不含 BASE_URL)
  11. * @param {string} [options.method='GET'] - 请求方法
  12. * @param {Object} [options.data] - 请求数据
  13. * @param {Object} [options.header] - 额外请求头
  14. * @param {boolean} [options.needToken=true] - 是否需要携带 Token
  15. * @returns {Promise}
  16. */
  17. export default function request(options = {}) {
  18. const {
  19. url,
  20. method = 'GET',
  21. data,
  22. header = {},
  23. needToken = true
  24. } = options
  25. // 构建请求头
  26. const headers = {
  27. 'Content-Type': 'application/json;charset=utf-8',
  28. 'clientid': CLIENT_ID,
  29. 'X-Platform-Code': PLATFORM_CODE,
  30. ...header
  31. }
  32. // 携带 Token
  33. if (needToken) {
  34. const token = getToken()
  35. if (token) {
  36. headers['Authorization'] = 'Bearer ' + token
  37. }
  38. }
  39. return new Promise((resolve, reject) => {
  40. uni.request({
  41. url: BASE_URL + url,
  42. method: method.toUpperCase(),
  43. data,
  44. header: headers,
  45. timeout: 600000,
  46. success: (res) => {
  47. console.log(res)
  48. const statusCode = res.statusCode
  49. const code = res.data.code
  50. const msg = res.data.msg
  51. const result = res.data.data
  52. // HTTP 状态码错误
  53. // if (statusCode === 401) {
  54. // // Token 过期或未登录
  55. // clearAuth()
  56. // uni.showToast({ title: '登录已过期,请重新登录', icon: 'none' })
  57. // setTimeout(() => {
  58. // uni.reLaunch({ url: '/pages/login/index' })
  59. // }, 1500)
  60. // return reject(new Error('未授权'))
  61. // }
  62. if (statusCode !== 200) {
  63. const errorMsg = msg || `请求失败(${statusCode})`
  64. uni.showToast({ title: errorMsg, icon: 'none' })
  65. return reject(new Error(errorMsg))
  66. }
  67. if (code === 401) {
  68. // Token 过期或未登录
  69. clearAuth()
  70. uni.showToast({ title: '登录已过期,请重新登录', icon: 'none' })
  71. setTimeout(() => {
  72. uni.reLaunch({ url: '/pages/login/index' })
  73. }, 1500)
  74. return reject(new Error('未授权'))
  75. }
  76. // 业务状态码
  77. if (code !== undefined && code !== 200) {
  78. const errorMsg = msg || '操作失败'
  79. uni.showToast({ title: errorMsg, icon: 'none' })
  80. return reject(new Error(errorMsg))
  81. }
  82. resolve(res.data)
  83. },
  84. fail: (err) => {
  85. uni.showToast({ title: '网络异常,请检查网络状态', icon: 'none' })
  86. reject(err)
  87. }
  88. })
  89. })
  90. }