request.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import store from '@/store'
  2. import configs from '@/config'
  3. import {
  4. getAccessToken
  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 baseUrls = configs.baseUrl;
  14. const request = config => {
  15. // 是否需要设置 token
  16. const isToken = (config.headers || {}).isToken === false
  17. config.header = config.header || {}
  18. if (getAccessToken() && !isToken) {
  19. config.header['Authorization'] = 'Bearer ' + getAccessToken()
  20. }
  21. // 设置租户 TODO 芋艿:强制 1 先
  22. config.header['tenant-id'] = '1';
  23. if (config.baseUrl) {
  24. config.url = config.baseUrl + config.url
  25. } else {
  26. config.url = baseUrls + config.url
  27. }
  28. // get请求映射params参数
  29. if (config.params) {
  30. let url = config.url + '?' + tansParams(config.params)
  31. url = url.slice(0, -1)
  32. config.url = url
  33. }
  34. return new Promise((resolve, reject) => {
  35. uni.request({
  36. method: config.method || 'get',
  37. timeout: config.timeout || timeout,
  38. url: config.url,
  39. data: config.data,
  40. // header: config.header,
  41. header: config.header,
  42. dataType: 'json'
  43. }).then(response => {
  44. let [error, res] = response
  45. if (error) {
  46. toast('后端接口连接异常')
  47. reject('后端接口连接异常')
  48. return
  49. }
  50. const code = res.data.code || 200
  51. const msg = errorCode[code] || res.data.msg || errorCode['default']
  52. if (code === 401) {
  53. showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  54. if (res.confirm) {
  55. store.dispatch('LogOut').then(res => {
  56. uni.reLaunch({
  57. url: '/pages/login'
  58. })
  59. })
  60. }
  61. })
  62. reject('无效的会话,或者会话已过期,请重新登录。')
  63. } else if (code === 500) {
  64. toast(msg)
  65. reject('500')
  66. } else if (code !== 200) {
  67. toast(msg)
  68. reject(code)
  69. }
  70. resolve(res.data)
  71. })
  72. .catch(error => {
  73. let {
  74. message
  75. } = error
  76. if (message === 'Network Error') {
  77. message = '后端接口连接异常'
  78. } else if (message.includes('timeout')) {
  79. message = '系统接口请求超时'
  80. } else if (message.includes('Request failed with status code')) {
  81. message = '系统接口' + message.substr(message.length - 3) + '异常'
  82. }
  83. toast(message)
  84. reject(error)
  85. })
  86. })
  87. }
  88. export default request