requests.js 2.5 KB

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