request.ts 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import store from '@/store'
  2. import config from '@/config'
  3. import { getToken } from '@/utils/auth'
  4. import errorCode from '@/utils/errorCode'
  5. import { toast, showConfirm, tansParams } from '@/utils/common'
  6. import { RequestConfig, ResponseData } from '@/types/request'
  7. let timeout = 600000
  8. const baseUrl = config.baseUrl
  9. const request = <T>(config:RequestConfig):Promise<ResponseData<T>> => {
  10. // 是否需要设置 token
  11. const isToken = (config.headers || {}).isToken === false
  12. config.header = config.header || {}
  13. if (getToken() && !isToken) {
  14. config.header['Authorization'] = 'Bearer ' + getToken()
  15. }
  16. // get请求映射params参数
  17. if (config.params) {
  18. let url = config.url + '?' + tansParams(config.params)
  19. url = url.slice(0, -1)
  20. config.url = url
  21. }
  22. return new Promise((resolve, reject) => {
  23. uni.request({
  24. method: config.method || 'GET',
  25. timeout: config.timeout || timeout,
  26. url: config.baseUrl || baseUrl + config.url,
  27. data: config.data,
  28. header: config.header,
  29. dataType: 'json'
  30. }).then(response => {
  31. /* let [error, res] = response
  32. if (error) {
  33. toast('后端接口连接异常')
  34. reject('后端接口连接异常')
  35. return
  36. } */
  37. const res = response
  38. const data:ResponseData<T> = res.data as ResponseData<T>
  39. const code = data.code || 200
  40. // @ts-ignore
  41. const msg:string = errorCode[code] || data.msg || errorCode['default']
  42. if (code === 401) {
  43. showConfirm('您还未登陆系统,是否前往登陆?').then(res => {
  44. if (res.confirm) {
  45. store.dispatch('LogOut').then(res => {
  46. uni.reLaunch({ url: '/pages/login' })
  47. })
  48. }
  49. })
  50. // uni.showToast({
  51. // title: '登陆后可以享受更多的服务哦',
  52. // icon: 'none',
  53. // });
  54. // setTimeout(() => {
  55. // store.dispatch('LogOut').then(res => {
  56. // uni.reLaunch({ url: '/pages/login' })
  57. // })
  58. // }, 500);
  59. reject('无效的会话,或者会话已过期,请重新登录。')
  60. } else if (code === 500) {
  61. toast(msg)
  62. reject('500')
  63. } else if (code !== 200) {
  64. toast(msg)
  65. reject(code)
  66. }
  67. resolve(data)
  68. })
  69. .catch(error => {
  70. let { message } = error
  71. uni.hideLoading()
  72. if (message === 'Network Error') {
  73. message = '后端接口连接异常'
  74. } else if (message.includes('timeout')) {
  75. message = '系统接口请求超时'
  76. } else if (message.includes('Request failed with status code')) {
  77. message = '系统接口' + message.substr(message.length - 3) + '异常'
  78. }
  79. toast(message)
  80. reject(error)
  81. })
  82. })
  83. }
  84. export default request