request.js 2.5 KB

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