request.js 2.5 KB

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