request.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import store from '@/store'
  2. import config from '@/config'
  3. import {
  4. getToken
  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 = 10000
  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. } else {
  21. uni.reLaunch({
  22. url: '/pages/login/index'
  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. return new Promise((resolve, reject) => {
  32. uni.request({
  33. method: config.method || 'get',
  34. timeout: config.timeout || timeout,
  35. url: config.baseUrl || baseUrl + config.url,
  36. data: config.data,
  37. header: config.header,
  38. dataType: 'json'
  39. }).then(response => {
  40. let [error, res] = response
  41. if (error) {
  42. toast('后端接口连接异常')
  43. reject('后端接口连接异常')
  44. return
  45. }
  46. console.log(res)
  47. const code = res.data.code || 200
  48. const msg = errorCode[code] || res.data.message || errorCode['default']
  49. if (code === 1011004) {
  50. showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  51. if (res.confirm) {
  52. if (getToken()) {
  53. store.dispatch('LogOut').then(res => {
  54. uni.reLaunch({
  55. url: '/pages/login/index'
  56. })
  57. })
  58. } else {
  59. uni.reLaunch({
  60. url: '/pages/login/index'
  61. })
  62. }
  63. }
  64. })
  65. reject('无效的会话,或者会话已过期,请重新登录。')
  66. }
  67. resolve(res.data)
  68. })
  69. .catch(error => {
  70. let {
  71. message
  72. } = error
  73. if (message === 'Network Error') {
  74. message = '后端接口连接异常'
  75. } else if (message.includes('timeout')) {
  76. message = '系统接口请求超时'
  77. } else if (message.includes('Request failed with status code')) {
  78. message = '系统接口' + message.substr(message.length - 3) + '异常'
  79. }
  80. toast(message)
  81. reject(error)
  82. })
  83. })
  84. }
  85. export default request