您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

106 行
2.9 KiB

  1. import config from './config.js'
  2. import { guid, getNonce, getVersion, getClient, isLoginTop } from './util.js'
  3. let BASE_URL = config.BASE_URL
  4. // #ifdef H5
  5. // H5 通过 manifest.json 的 devServer.proxy 代理到 /api,规避跨域
  6. BASE_URL = '/api'
  7. // #endif
  8. /**
  9. * 统一请求封装(沿用旧版鉴权约定)
  10. * - 自动附加 token / uid / mac / client / source / version 等公共参数
  11. * - 响应 code===0 视为成功;code===1009 登录失效,清空登录态并跳转登录
  12. * @param {{ url: string, method?: string, params?: object, headers?: object, loading?: boolean }} options
  13. */
  14. export default function request({
  15. url = '',
  16. method = 'GET',
  17. params = {},
  18. headers = {},
  19. loading = false
  20. } = {}) {
  21. const fullUrl = BASE_URL + url
  22. const timestamp = parseInt(Date.now() / 1000)
  23. const token = uni.getStorageSync('token')
  24. const uid = uni.getStorageSync('open_id')
  25. let mac = uni.getStorageSync('mac')
  26. const source = uni.getStorageSync('source') || ''
  27. if (!mac) {
  28. const sysInfo = uni.getSystemInfoSync()
  29. mac = sysInfo.deviceId || guid()
  30. uni.setStorageSync('mac', mac)
  31. }
  32. const { timeStr, nonce } = getNonce()
  33. const { version, version_code } = getVersion()
  34. const header = Object.assign(
  35. {
  36. 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
  37. timestr: timeStr,
  38. nonce
  39. },
  40. headers
  41. )
  42. if (token) header.token = token
  43. let data = {
  44. token,
  45. uid,
  46. mac,
  47. base_timestamp: timestamp,
  48. client: getClient(),
  49. source,
  50. client_ios: uni.getSystemInfoSync().platform === 'ios' ? 1 : 0,
  51. version,
  52. version_code,
  53. ...params
  54. }
  55. // 去除空字符串字段
  56. Object.keys(data).forEach((k) => {
  57. if (data[k] === '') delete data[k]
  58. })
  59. if (loading) uni.showLoading({ mask: true, title: '加载中...' })
  60. return new Promise((resolve, reject) => {
  61. uni.request({
  62. url: fullUrl,
  63. method,
  64. header,
  65. data
  66. })
  67. .then((response) => {
  68. const res = (response && response.data) || {}
  69. if (res.code === 0) {
  70. resolve(res)
  71. } else if (res.code === 1009) {
  72. // 登录失效:清空登录态并跳转登录页
  73. // 动态引入避免循环依赖
  74. import('@/store/user.js').then(({ useUserStore }) => {
  75. useUserStore().clear()
  76. })
  77. if (!isLoginTop()) {
  78. let loginUrl = '/pages/login/login'
  79. // #ifdef H5
  80. loginUrl += `?redirect=${encodeURIComponent(location.pathname + location.search)}`
  81. // #endif
  82. uni.navigateTo({ url: loginUrl })
  83. }
  84. reject(res)
  85. } else {
  86. reject(res)
  87. }
  88. })
  89. .catch((e) => {
  90. const status = e && e.statusCode
  91. reject({ code: 1, msg: status ? `网络异常 (${status})` : '网络异常,请重试!' })
  92. })
  93. .finally(() => {
  94. if (loading) uni.hideLoading()
  95. })
  96. })
  97. }