request.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 = errorCode[code] || res.data.msg || errorCode['default']
  45. if (code === 401) {
  46. showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  47. if (res.confirm) {
  48. uni.reLaunch({
  49. url: '/pages/login/index'
  50. })
  51. }
  52. })
  53. reject('无效的会话,或者会话已过期,请重新登录。')
  54. } else if (code === 405) {
  55. showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  56. if (res.confirm) {
  57. uni.reLaunch({
  58. url: '/pages/login/index'
  59. })
  60. }
  61. })
  62. reject('无效的会话,或者会话已过期,请重新登录。')
  63. } else if (code === 500) {
  64. toast("数据异常-500")
  65. reject('500')
  66. } else if (code !== 0) {
  67. // toast(msg)
  68. reject(code)
  69. }
  70. resolve(res)
  71. })
  72. .catch(error => {
  73. let {
  74. message
  75. } = error
  76. if (message === 'Network Error') {
  77. message = '后端接口连接异常'
  78. } else if (message.includes('timeout')) {
  79. message = '系统接口请求超时'
  80. } else if (message.includes('Request failed with status code')) {
  81. message = '系统接口' + message.substr(message.length - 3) + '异常'
  82. }
  83. toast(message)
  84. reject(error)
  85. })
  86. })
  87. }
  88. export default request