request.js 2.5 KB

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