You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.2 KiB

5 months ago
5 months ago
5 months ago
5 months ago
  1. import store from '@/store'
  2. import {
  3. getToken
  4. } from '@/utils/auth'
  5. import errorCode from '@/utils/errorCode'
  6. import {
  7. toast,
  8. showConfirm,
  9. tansParams
  10. } from '@/utils/common'
  11. import {
  12. currentUrl
  13. } from '@/utils/getUrl'
  14. let timeout = 10000
  15. const baseUrl = currentUrl
  16. const request = config => {
  17. // 是否需要设置 token
  18. const isToken = (config.headers || {}).isToken || false
  19. config.header = config.header || {}
  20. if (getToken() && isToken) {
  21. config.header['Authorization'] = 'Bearer ' + getToken()
  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. return new Promise((resolve, reject) => {
  30. uni.request({
  31. method: config.method || 'get',
  32. timeout: config.timeout || timeout,
  33. url: config.baseUrl || baseUrl + config.url,
  34. data: config.data,
  35. header: config.header,
  36. dataType: 'json'
  37. }).then(response => {
  38. let [error, res] = response
  39. if (error) {
  40. toast('后端接口连接异常')
  41. reject('后端接口连接异常')
  42. return
  43. }
  44. const code = res.data.code || 200
  45. const msg = errorCode[code] || res.data.msg || errorCode['default']
  46. if (code === 401) {
  47. store.dispatch('LogOut')
  48. showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  49. if (res.confirm) {
  50. store.dispatch('login').then(res => {
  51. uni.reLaunch({
  52. url: '/pages/index'
  53. })
  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(res.data)
  66. })
  67. .catch(error => {
  68. let {
  69. message
  70. } = error
  71. if (message === 'Network Error') {
  72. message = '后端接口连接异常'
  73. } else if (message.includes('timeout')) {
  74. message = '系统接口请求超时'
  75. } else if (message.includes('Request failed with status code')) {
  76. message = '系统接口' + message.substr(message.length - 3) + '异常'
  77. }
  78. toast(message)
  79. reject(error)
  80. })
  81. })
  82. }
  83. export default request