request.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 i18 from '@/utils/i18.js'
  7. let timeout = 10000
  8. const baseUrl = config.baseUrl
  9. const request = config => {
  10. // 是否需要设置 token
  11. const isToken = (config.headers || {}).isToken === false
  12. config.header = config.header || {}
  13. let hideLoadding = config.hideLoading;
  14. if (getToken() && !isToken) {
  15. config.header['Authorization'] = '' + getToken()
  16. }
  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. if(!hideLoadding){
  25. uni.showLoading({title:i18("正在加载")});
  26. }
  27. uni.request({
  28. method: config.method || 'get',
  29. timeout: config.timeout || timeout,
  30. url: config.baseUrl || baseUrl + config.url,
  31. data: config.data,
  32. header: config.header,
  33. dataType: 'json'
  34. }).then(response => {
  35. if(!hideLoadding){
  36. uni.hideLoading();
  37. }
  38. let [error, res] = response
  39. if (error) {
  40. toast(i18('后端接口连接异常'))
  41. reject(i18('后端接口连接异常'))
  42. return
  43. }
  44. const code = res.data.code || 200
  45. const msg = errorCode[code] || res.data.msg || errorCode['default']
  46. if (code === 401) {
  47. showConfirm(i18('登录状态已过期,您可以继续留在该页面,或者重新登录?')).then(res => {
  48. if (res.confirm) {
  49. store.dispatch('LogOut').then(res => {
  50. uni.reLaunch({ url: '/pages/login' })
  51. uni.setStorageSync("detailBack",false);
  52. })
  53. }
  54. })
  55. reject(i18('无效的会话,或者会话已过期,请重新登录。'))
  56. } else if (code === 500) {
  57. toast(i18(msg))
  58. reject('500')
  59. } else if (code !== 200) {
  60. toast(msg)
  61. reject(code)
  62. }
  63. resolve(res.data)
  64. })
  65. .catch(error => {
  66. let { message } = error
  67. if (message === 'Network Error') {
  68. message = '后端接口连接异常'
  69. } else if (message.includes('timeout')) {
  70. message = '系统接口请求超时'
  71. } else if (message.includes('Request failed with status code')) {
  72. message = '系统接口' + message.substr(message.length - 3) + '异常'
  73. }
  74. toast(message)
  75. reject(error)
  76. })
  77. })
  78. }
  79. export default request