request.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. success: (res) => {
  46. const statusCode = res.statusCode
  47. const result = res.data
  48. // HTTP 状态码错误
  49. if (statusCode === 401) {
  50. // Token 过期或未登录
  51. clearAuth()
  52. uni.showToast({ title: '登录已过期,请重新登录', icon: 'none' })
  53. setTimeout(() => {
  54. uni.reLaunch({ url: '/pages/login/login' })
  55. }, 1500)
  56. return reject(new Error('未授权'))
  57. }
  58. if (statusCode !== 200) {
  59. const msg = result?.msg || `请求失败(${statusCode})`
  60. uni.showToast({ title: msg, icon: 'none' })
  61. return reject(new Error(msg))
  62. }
  63. // 业务状态码
  64. if (result.code !== undefined && result.code !== 200) {
  65. const msg = result.msg || '操作失败'
  66. uni.showToast({ title: msg, icon: 'none' })
  67. return reject(new Error(msg))
  68. }
  69. resolve(result)
  70. },
  71. fail: (err) => {
  72. uni.showToast({ title: '网络异常,请稍后重试', icon: 'none' })
  73. reject(err)
  74. }
  75. })
  76. })
  77. }