request.js 2.8 KB

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