request.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import store from '@/store'
  2. import config from '@/config'
  3. import {
  4. getToken,getServerUrl
  5. } from '@/utils/auth'
  6. import errorCode from '@/utils/errorCode'
  7. import {
  8. toast,
  9. showConfirm,
  10. tansParams
  11. } from '@/utils/common'
  12. let timeout = 50000
  13. const baseUrl = config.baseUrl
  14. const request = config => {
  15. // 是否需要设置 token
  16. const isToken = (config.headers || {}).isToken === false
  17. config.header = config.header || {}
  18. if (getToken() && !isToken) {
  19. // config.header['Authorization'] = 'Bearer ' + getToken()
  20. config.header['UserKey'] = getToken()
  21. config.header['ServerUrl'] = getServerUrl()
  22. } else {
  23. uni.reLaunch({
  24. url: '/pages/login/index'
  25. })
  26. }
  27. // get请求映射params参数
  28. if (config.params) {
  29. let url = config.url + '?' + tansParams(config.params)
  30. url = url.slice(0, -1)
  31. config.url = url
  32. }
  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(response)
  43. let [error, res] = response
  44. if (error) {
  45. toast('后端接口连接异常')
  46. reject('后端接口连接异常')
  47. return
  48. }
  49. console.log(res)
  50. const code = res.data.Code || 200
  51. const msg = errorCode[code] || res.data.Msg || errorCode['default']
  52. console.log(code)
  53. if (msg == 'UNLOGIN') {
  54. showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  55. if (res.confirm) {
  56. console.log(getToken())
  57. if (getToken()) {
  58. store.dispatch('LogOut').then(res => {
  59. uni.reLaunch({
  60. url: '/pages/login/index'
  61. })
  62. })
  63. } else {
  64. uni.reLaunch({
  65. url: '/pages/login/index'
  66. })
  67. }
  68. }
  69. })
  70. reject('无效的会话,或者会话已过期,请重新登录。')
  71. }
  72. resolve(res.data)
  73. })
  74. .catch(error => {
  75. let {
  76. message
  77. } = error
  78. if (message === 'Network Error') {
  79. message = '后端接口连接异常'
  80. } else if (message.includes('timeout')) {
  81. message = '系统接口请求超时'
  82. } else if (message.includes('Request failed with status code')) {
  83. message = '系统接口' + message.substr(message.length - 3) + '异常'
  84. }
  85. toast(message)
  86. reject(error)
  87. })
  88. })
  89. }
  90. export default request