request.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // import { useUserStore } from '@/store/user.js'
  2. import config from '@/config'
  3. import { getSession } from '@/utils/auth'
  4. import errorCode from '@/utils/errorCode'
  5. import { toast, showConfirm, tansParams } from '@/utils/common'
  6. let timeout = config.timeout
  7. const baseUrl = config.baseUrl
  8. const request = config => {
  9. // 是否需要设置 token
  10. const isSession = config.isSession === false
  11. config.header = config.header || {}
  12. if (isSession) {
  13. if (getSession()) {
  14. config.header['cookie'] = getSession()
  15. } else {
  16. showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  17. // if (res.confirm) {
  18. // store.dispatch('LogOut').then(res => {
  19. // uni.reLaunch({ url: '/pages/login' })
  20. // })
  21. // }
  22. })
  23. reject('无效的会话,或者会话已过期,请重新登录。')
  24. }
  25. }
  26. // get请求映射params参数
  27. if (config.params) {
  28. let url = config.url + '?' + tansParams(config.params)
  29. url = url.slice(0, -1)
  30. config.url = url
  31. }
  32. console.log('request.config', config);
  33. return new Promise((resolve, reject) => {
  34. uni.request({
  35. method: config.method || 'get',
  36. timeout: config.timeout || timeout,
  37. url: config.baseUrl || baseUrl + config.url,
  38. data: config.data,
  39. header: config.header,
  40. dataType: 'json'
  41. }).then(response => {
  42. console.log('request.response', response);
  43. const { statusCode, data } = response
  44. const returnCode = data.returnCode
  45. const code = statusCode || 200
  46. const msg = errorCode[code] || data.returnMsg || errorCode['default']
  47. if (returnCode == -201) {
  48. toast(msg)
  49. reject(returnCode)
  50. return
  51. }
  52. if (code === 401) {
  53. showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  54. // if (res.confirm) {
  55. // store.dispatch('LogOut').then(res => {
  56. // uni.reLaunch({ url: '/pages/login' })
  57. // })
  58. // }
  59. })
  60. reject('无效的会话,或者会话已过期,请重新登录。')
  61. } else if (code === 500) {
  62. toast(msg)
  63. reject('500')
  64. } else if (code !== 200) {
  65. toast(msg)
  66. reject(code)
  67. }
  68. resolve(data)
  69. })
  70. .catch(error => {
  71. console.log('request.error', error);
  72. let { errMsg } = error
  73. if (errMsg === 'Network Error') {
  74. errMsg = '后端接口连接异常'
  75. } else if (errMsg.includes('timeout')) {
  76. errMsg = '系统接口请求超时'
  77. } else if (errMsg.includes('Request failed with status code')) {
  78. errMsg = '系统接口' + errMsg.substr(errMsg.length - 3) + '异常'
  79. } else if (errMsg.includes('request:fail')) {
  80. errMsg = '网络请求失败'
  81. }
  82. toast(errMsg)
  83. reject(error)
  84. })
  85. })
  86. }
  87. export default request