request.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import store from '@/store'
  2. import config from '@/config'
  3. import { getAccessToken,getTenantId} 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 + config.baseApi;
  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'] = getTenantId();
  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. uni.reLaunch({ url: '/' })
  43. // showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  44. // if (res.confirm) {
  45. // uni.reLaunch({ url: '/' })
  46. // }
  47. // })
  48. reject('无效的会话,或者会话已过期,请重新登录。')
  49. } else if (code === 500) {
  50. toast(msg)
  51. reject('500')
  52. } else if (code !== 200) {
  53. toast(msg)
  54. reject(code)
  55. }
  56. resolve(res.data)
  57. })
  58. .catch(error => {
  59. let { message } = error
  60. if (message === 'Network Error') {
  61. message = '后端接口连接异常'
  62. } else if (message.includes('timeout')) {
  63. message = '系统接口请求超时'
  64. } else if (message.includes('Request failed with status code')) {
  65. message = '系统接口' + message.substr(message.length - 3) + '异常'
  66. }
  67. toast(message)
  68. reject(error)
  69. })
  70. })
  71. }
  72. export default request