request.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 {
  10. toast,
  11. showConfirm,
  12. tansParams
  13. } from '@/utils/common'
  14. let timeout = 10000
  15. const baseUrl = config.baseUrl
  16. const request = config => {
  17. // 是否需要设置 token
  18. // const isToken = (config.headers || {}).isToken === false
  19. config.header = config.header || {}
  20. // if (getToken() && !isToken) {
  21. // config.headers['X-AUTH-SIGN'] = Md5.hashStr(JSON.stringify(config.data) +auth.secret);
  22. // config.headers['X-AUTH-TOKEN'] = auth.token;
  23. // }
  24. if (getAuth()) {
  25. config.headers['X-AUTH-SIGN'] = Md5.hashStr(JSON.stringify(config.data) + JSON.parse(getAuth()).secret);
  26. config.headers['X-AUTH-TOKEN'] = JSON.parse(getAuth()).token;
  27. }
  28. return new Promise((resolve, reject) => {
  29. // debugger
  30. uni.request({
  31. method: config.method || 'get',
  32. timeout: config.timeout || timeout,
  33. url: config.baseUrl || baseUrl + config.url,
  34. data: config.data,
  35. header: config.headers,
  36. dataType: 'json'
  37. }).then(response => {
  38. const res = response.data;
  39. // if (error) {
  40. // toast('后端接口连接异常')
  41. // reject('后端接口连接异常')
  42. // return
  43. // }
  44. const code = res.code
  45. // const msg = errorCode[code] || res.data.msg || errorCode['default']
  46. if (code === 401) {
  47. showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
  48. // if (res.confirm) {
  49. // store.dispatch('LogOut').then(res => {
  50. // uni.reLaunch({ url: '/pages/login' })
  51. // })
  52. // }
  53. uni.reLaunch({
  54. url: '/pages/login'
  55. })
  56. })
  57. reject('无效的会话,或者会话已过期,请重新登录。')
  58. } else if (code === 405) {
  59. showConfirm('帐号已在其他设备登录').then(res => {
  60. uni.reLaunch({
  61. url: '/pages/login'
  62. })
  63. })
  64. } else if (code === 500) {
  65. reject('500')
  66. } else if (code !== 0) {
  67. toast(res.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