request.js 2.8 KB

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