request.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. //import store from '@/store'
  2. import config from '../config.js'
  3. import cacheManager from '@/utils/cacheManager.js'
  4. import {
  5. Md5
  6. } from 'ts-md5/dist/md5';
  7. import errorCode from '@/utils/errorCode'
  8. import {
  9. toast,
  10. showConfirm,
  11. tansParams
  12. } from '@/utils/common'
  13. let timeout = 10000
  14. const baseUrl = config.baseUrl
  15. const request = config => {
  16. // 是否需要设置 token
  17. // const isToken = (config.headers || {}).isToken === false
  18. config.header = config.header || {}
  19. // if (getToken() && !isToken) {
  20. // config.headers['X-AUTH-SIGN'] = Md5.hashStr(JSON.stringify(config.data) +auth.secret);
  21. // config.headers['X-AUTH-TOKEN'] = auth.token;
  22. // }
  23. if (cacheManager.get('auth')) {
  24. config.headers['X-AUTH-SIGN'] = Md5.hashStr(JSON.stringify(config.data) + cacheManager.get('auth').secret);
  25. config.headers['X-AUTH-TOKEN'] =cacheManager.get('auth').token;
  26. }
  27. return new Promise((resolve, reject) => {
  28. // debugger
  29. uni.request({
  30. method: config.method || 'get',
  31. timeout: config.timeout || timeout,
  32. url: config.baseUrl || baseUrl + config.url,
  33. data: config.data,
  34. header: config.headers,
  35. dataType: 'json'
  36. }).then(response => {
  37. const res = response.data;
  38. // if (error) {
  39. // toast('后端接口连接异常')
  40. // reject('后端接口连接异常')
  41. // return
  42. // }
  43. const code = res.code
  44. const msg = res.msg
  45. // const msg = errorCode[code] || res.data.msg || errorCode['default']
  46. if (code === 401) {
  47. showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  48. if (res.confirm) {
  49. uni.reLaunch({
  50. url: '/pages/login/index'
  51. })
  52. }
  53. })
  54. reject('无效的会话,或者会话已过期,请重新登录。')
  55. } else if (code === 405) {
  56. showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  57. if (res.confirm) {
  58. uni.reLaunch({
  59. url: '/pages/login/index'
  60. })
  61. }
  62. })
  63. reject('无效的会话,或者会话已过期,请重新登录。')
  64. } else if (code === 500) {
  65. toast("数据异常-500")
  66. reject('500')
  67. }else if (code === 400) {
  68. toast("数据异常-400")
  69. reject('400')
  70. } else if (code !== 0) {
  71. toast(msg)
  72. reject(code)
  73. }
  74. resolve(res)
  75. })
  76. .catch(error => {
  77. let {
  78. message
  79. } = error
  80. if (message === 'Network Error') {
  81. message = '后端接口连接异常'
  82. } else if (message.includes('timeout')) {
  83. message = '系统接口请求超时'
  84. } else if (message.includes('Request failed with status code')) {
  85. message = '系统接口' + message.substr(message.length - 3) + '异常'
  86. }
  87. toast(message)
  88. reject(error)
  89. })
  90. })
  91. }
  92. export default request